Current Offer on Pentesting Exam: 80 % Off on All Our Penetesting Exams, Coupon Code: ANNIVERSARY-80-OFF

A Pentester’s Guide to NoSQL Injection

A Pentester’s Guide to NoSQL Injection

Hello readers! In this blog post, our Senior Consultant Aditya has discussed the infamous NoSQL injection vulnerability. He has explained the vulnerability in depth, the prerequisites, attack vectors, how the vulnerability works in the background, recommendations, practice labs for hands-on, and more. We’ll cover everything from the basics of NoSQL injection to specific attack vectors in popular NoSQL databases like MongoDB, Couchbase, ElasticSearch, Redis, Memcached, and CouchDB.


Additionally, we’ll discuss the tools and techniques that security researchers can use to detect and exploit NoSQL injection vulnerabilities. We’ll also provide practice labs for readers who want to further develop their NoSQL injection skills and gain hands-on experience with attacking NoSQL databases.


By the end of this article, you’ll have a solid understanding of NoSQL injection attacks and their exploitation, which will help you identify vulnerabilities in web applications and improve their security. So, let’s dive into the world of NoSQL injection and learn how to hack non-relational databases like a pro!


●       NoSQL injection targets non-relational databases, including document-oriented databases, key-value stores, and graph databases. While NoSQL databases are becoming increasingly popular due to their scalability, flexibility, and ease of use, they are also vulnerable to injection attacks that can compromise the confidentiality, integrity, and availability of data. It is important to be aware of these vulnerabilities and know how to exploit them to test the security of web applications.

●       NoSQL injection attacks can allow attackers to read or modify sensitive data, execute arbitrary code, or even take control of the entire NoSQL database.

Structured Query Language (SQL)

SQL databases have been around for decades and are the most commonly used type of database in web applications. These databases use Structured Query Language (SQL) to store and retrieve data in a structured format, making them easy to use and efficient. However, they are also vulnerable to SQL injection attacks, which can allow attackers to execute malicious SQL statements and gain access to sensitive data or even take control of the database.


SQL injection attacks occur when an attacker inputs malicious SQL statements into a vulnerable application’s input fields, such as login forms, search fields, or contact forms. If the application fails to properly validate and sanitise the input, the attacker’s malicious SQL statement could get executed by the database, leading to unintended and often catastrophic results.


Some common types of SQL injection attacks are:

●       Union-based SQL injection: An attacker uses the UNION operator to combine two SELECT statements, allowing them to extract data from the database that they shouldn’t have access to.

●       Error-based SQL injection: An attacker uses an invalid input value to trigger an error message from the database, which supposedly reveals information about the structure and content of the database.

●       Blind SQL injection: An attacker uses boolean-based or time-based techniques to extract information from the database without seeing the actual output.

Not only SQL (NoSQL)

Unlike SQL databases, NoSQL databases are designed to store and retrieve unstructured or semi-structured data. They are flexible, scalable, and can handle large volumes of data efficiently. However, they are also vulnerable to NoSQL injection attacks, which can have consequences similar to SQL injection attacks, including data theft and application compromise.


NoSQL injection attacks occur when an attacker inputs malicious data into an application’s input fields that interact with a NoSQL database, such as a search field or a comment form. If the application fails to properly validate and sanitise the input, the attacker’s malicious code can be executed by the NoSQL database, leading to unintended and often catastrophic results.


Some common types of NoSQL injection attacks include:

●       Command injection: An attacker inputs a command that is interpreted as code by the NoSQL database, allowing them to execute arbitrary commands on the server.

●       Object injection: An attacker inputs a serialized object which is deserialized by the application and executed on the server, allowing them to gain access to sensitive data or execute arbitrary code.

●       JavaScript injection: An attacker inputs JavaScript code that is executed by the client-side application, allowing them to steal user data or manipulate the application’s behaviour.

SQL Injection vs NoSQL Injection

The following table provides a brief comparison of features and attributes between NoSQL and SQL databases.



NoSQL Databases

SQL Databases


There is no single declarative query language, and it is totally dependent on the database type.

Structured Query Language (SQL) is used for writing queries.


No predefined schema.

Uses a predefined schema.


Horizontal and Vertical Scalability.

Vertical Scalability.


Supports distributed systems.

Generally, not suitable for distributed systems.


Generally used for big data applications.

Generally used for smaller applications or projects.


Provides better performance for large datasets and write-heavy workloads, such as social media applications.

Can experience performance issues with large datasets but performs well with read-heavy workloads, such as data warehousing.


Organises and stores data in the form of key-value, column-oriented documents, and graphs.

Organises and stores data in the form of tables and fixed columns and rows.


Offers simpler data modelling, providing a better fit for hierarchical data structures.

Limited to a flat relational model, which is not well-suited for hierarchical data.


Provides high availability, allowing for uninterrupted access to data in the event of a node failure.

High availability requires complex setups such as clustering and replication.

Data Types

Can handle a variety of data types, including multimedia

Limited to handling structured data types

NoSQLi in MongoDB

In MongoDB, data is stored as BSON (Binary JSON) documents, which are similar to JSON objects but with some additional data types. MongoDB uses a query language called the MongoDB Query Language (MQL) to manipulate and retrieve data from these documents. For example, a query to retrieve a user with a specific username might look like this:

In this query, the find() method is called on the users collection in the db database, and the query object {username: “secops”} is passed as an argument. This query would retrieve all documents in the users collection where the username field is equal to “secops”.

However, if user input is passed directly into the query without any validation or sanitization, an attacker could exploit this vulnerability by entering a specially crafted value that modifies the query in some way. For example, an attacker could enter a value for the username field like this:

This value would be interpreted by MongoDB as a greater than comparison with an empty string. The resulting query would look like this:

This query would match all documents in the users collection where the username field is greater than an empty string, which would effectively match all documents in the collection. An attacker could use this technique to retrieve sensitive data or modify data in unintended ways.


Now let us try to develop a better understanding using another example. Let us take the following MQL query:

An attacker might be able to modify this query by adding additional query parameters that  could change its behaviour:

This modified query would return all user documents where the username is secops and the password is not null. An attacker could use this technique to bypass authentication and gain access to sensitive data.

NoSQLi in ElasticSearch

Elasticsearch is a powerful NoSQL database that is designed for indexing and searching large amounts of data quickly and efficiently. It is widely used in many applications, including e-commerce, social media, and financial services. However, like any other database, Elasticsearch is vulnerable to attacks, including NoSQL injection.


In Elasticsearch, NoSQL injection attacks can occur when an application accepts user input and uses it to construct Elasticsearch queries without proper validation or sanitization. This can allow an attacker to inject malicious code into the query parameters and manipulate the query in unexpected ways.

For example, consider the following Elasticsearch query that searches for documents with a specific ID:

This query searches for documents in the index index_name that have an ID of 123. However, an attacker could inject the following code into the ID parameter to retrieve all documents from the index:

This would result in the following query:

The OR operator would cause the query to match all documents in the index, allowing the attacker to retrieve sensitive information.

NoSQLi in Redis

Redis is a popular NoSQL database system that is widely used for its high performance and low latency. However, like many NoSQL databases, Redis is vulnerable to NoSQL injection attacks. Redis commands are sent using a text-based protocol called Redis Serialization Protocol (RESP). This protocol uses a simple format where each command is composed of one or more strings, with each string separated by a newline character. For example, the Redis command to set a key-value pair might look like this:

In a NoSQL injection attack, an attacker can manipulate the above command by adding additional commands or changing the arguments of the existing commands. For example, an attacker might try to inject a command to delete all keys in the database by appending the following command to the end of the SET command:

This command would set the value of the mykey key to myvalue, and then delete all keys in the database.

NoSQLi in Memcached

Memcached is a widely-used distributed in-memory caching system that is often used to speed up the performance of web applications. However, it is not immune to security vulnerabilities, and one such vulnerability is the Memcached NoSQL injection.


The Memcached NoSQL injection vulnerability occurs when an attacker sends a specially-crafted request to the Memcached server. The request contains a payload that is designed to exploit the vulnerability in the application. The payload can be a combination of various techniques, such as command injection, SQL injection, or cross-site scripting (XSS).


The most common technique used in Memcached NoSQL injection attacks is command injection. In command injection, the attacker sends a request that contains a command that the application will execute on the Memcached server. The command can be a system command, such as ls or cat or a Memcached-specific command, such as stats or get. The attacker can then use the output from the executed command to gather sensitive information or execute additional commands.


Consider the following Python code that sends a GET request to a Memcached server to retrieve a value based on a user-provided key:

In this code, the user is prompted to enter the key that is to be retrieved from the Memcached server. The memcache library is used to create a client connection to the server and retrieve the value associated with the key. If the value exists, it is printed to the console. Otherwise, an error message is printed.

However, this code is vulnerable to Memcached NoSQL injection attacks. An attacker could provide a malicious key such as ‘; system(“rm -rf /”); #, which would cause the following query to be executed on the server:

This would execute the rm -rf / command on the server, which would delete all files and directories on the server.

To prevent Memcached NoSQL injection attacks, it is important to sanitise user input and use parameterized queries. Here’s an example of how to modify the previous code to prevent Memcached NoSQL injection attacks:

In this modified code, the user input is sanitized to remove any semicolons, dashes, or pound signs, which are commonly used in Memcached NoSQL injection attacks. The get_multi() method of the memcache library is used to retrieve the value associated with the sanitized key. The value variable is a dictionary containing all the keys and values returned by the server, so the value associated with the sanitized key is accessed using value[key]. This ensures that the user input is properly sanitized and prevents Memcached NoSQL injection attacks.

NoSQLi in CouchDB

In CouchDB, NoSQL injection can occur when an attacker submits a malicious query to the database that is not properly sanitized or validated. This can lead to unauthorised access to sensitive data, modification of data, or even deletion of entire databases.


The following example shows a code snippet in JavaScript using the Nano library to interact with a CouchDB database:

In this example, the code is vulnerable to NoSQL injection because it is directly using user input (username and password) in a query to retrieve user data from the database (db.get(‘users’, username, …)) without any validation or sanitization.

An attacker could exploit this vulnerability by submitting a malicious username or password that contains special characters, such as $, |, &, ;, etc. that could alter the structure of the query and potentially allow unauthorised access or manipulation of data.

To prevent NoSQL injection in the above-mentioned example, the code should use parameterized queries and input validation to ensure that user input is properly sanitized and validated. For example:

In this updated example, the code uses a parameterized query (db.view) that specifies the key to search for (username) and properly validates the input to ensure that it is not empty or null. Additionally, the code uses a view to retrieve user data instead of directly querying the database to improve security and efficiency.


Although complex in nature, the NoSQL injection vulnerability can be detected by performing the following steps:

●       Understand the syntax and query language used by each NoSQL database to detect NoSQL injection.

●       Analyse the database’s API, documentation, and code samples to identify valid syntax and parameters.

●       Attempt to inject malicious input into the database and observe its response.

●       Craft payloads that can bypass input validation and filtering mechanisms to execute arbitrary code or leak sensitive data.

●       Utilize tools like NoSQLMap and Nosql-Exploitation-Framework to automate the detection process and provide a comprehensive report of the attack surface.


NoSQLMap is an open-source penetration testing tool designed to detect and exploit NoSQL injection vulnerabilities. The tool automates the process of discovering NoSQL injection flaws by testing the target application against known injection vectors and payloads. It supports multiple NoSQL databases, including MongoDB, Cassandra, and CouchDB, and can perform various tasks such as dumping data, brute-forcing passwords, and executing arbitrary commands. NoSQLMap uses a command-line interface (CLI) and offers a range of options and switches to customise the attack vectors and techniques used. The tool also supports scripting and can be integrated with other security testing tools such as Metasploit and Nmap.


The NoSQLMap tool provides a command-line interface which can be accessed by opening the terminal and navigating to the directory where NoSQLMap is installed. Execute the following command to test the target application:

Replace <target_url> with the URL of the target application. You can use options like -d to specify the target database, -p to specify the port, and -v to enable verbose output. For example, if you want to test a MongoDB database running on port 27017, the command would be:

NoSQLMap supports multiple injection techniques like boolean-based, error-based, and time-based. You can use the -t option to specify the technique you want to use. For example, to use a boolean-based technique, you can use the following command:

NoSQLMap comes with a set of predefined payloads that can be used to test for NoSQL injection vulnerabilities. You can also create custom payloads using the –eval option. For example, to use a custom payload, you can use the following command:

NoSQLMap will generate a report of the vulnerabilities it finds, including the type of injection, the affected parameter, and the payload used to exploit it. You can use this information to further test and exploit the vulnerabilities. For example, if NoSQLMap finds a vulnerability, you can use the –sql-shell option to get a shell on the database and execute commands.


The NoSQL Exploitation Framework (NoSQL-Exploitation-Framework) is a tool that is used to audit and exploit NoSQL databases. It is an open-source project that provides various modules and plugins to automate the process of detecting and exploiting NoSQL injection vulnerabilities in various databases like MongoDB, CouchDB, Redis, and Cassandra.


The NoSQL-Exploitation-Framework tool provides a command-line interface and a web interface that can be used to scan and test the target NoSQL database for various vulnerabilities. It supports different types of attacks, including remote code execution, SQL injection, cross-site scripting (XSS), and file retrieval. The tool can also perform brute-force attacks to guess weak passwords and usernames.


The NoSQL-Exploitation-Framework tool can be installed on various operating systems, including Linux, macOS, and Windows, and requires Python and Pip to be installed. It is highly customizable and allows users to write their own modules and plugins to extend the functionality of the tool.


Launch the NoSQL-Exploitation-Framework tool and execute the following command:

This will start the NoSQL-Exploitation-Framework tool in command-line mode.


Once the NoSQL-Exploitation-Framework is launched, you need to configure the database connection by using the set command, followed by the database details. For example, to configure a MongoDB connection, you can use the following command:


Replace the <username>, <password>, <hostname>, <port>, and <database_name> with the actual values of your MongoDB instance.


You can then list the available modules in the NoSQL-Exploitation-Framework tool by using the show modules command. This will display a list of all the available modules along with their descriptions.


To load a module, use the use command followed by the name of the module. For example, to load the MongoDB remote code execution module, use the following command:

After loading the module, you need to set the required parameters by using the set command followed by the parameter name and value. For example, to set the target IP address and port, you can use the following commands:

Finally, you can run the exploit by using the run command. This will execute the command and attempt to exploit the vulnerability in the target NoSQL database.


The output of the exploit will be displayed on the screen, which will include details about the vulnerability and whether the exploit was successful or not.

Practice Labs

Find The Flag

As a team of advanced penetration testers and security researchers, we passionately believe in a hands-on approach to cyber security. As a result, we have published a NoSQL Injection practice lab on our platform Vulnmachines. Learners can further understand this vulnerability and its exploitation by practising it in our labs which reflect real-life situations.


On starting the lab and navigating to the home page, we can observe that three types of NoSQL injection labs are available for us, let’s select Find The Flag for now, as shown below:

On navigating to Find The Flag lab we can observe that a page titled JavaScript Injection appears on the screen. The page also mentions that we have to exploit NoSQLi for determining other users of the application, as shown below:

Since our goal in this scenario is to discover all users, we’d like to inject a payload that would always evaluate to true. If we inject a string such as  ‘ || ‘1’==’1 , the query in the backend becomes $where: `this.username == ” || ‘1’==’1’`, which always evaluates to true and therefore returns all results, as shown below:

Bypass Login

On starting the lab and navigating to the home page, we can observe that a login page appears on the screen which mentions that the login form is vulnerable to MongoDB Verb Injection vulnerability, as shown below:

To perform this attack, capture the login request via Burp Suite proxy and send it to the repeater tab.


Add the below-mentioned payload in the username and password fields, and observe that the attack is successful and we can view the flag in the response body, as shown below:

Find Admin Password

On starting the lab and navigating to the home page, we can observe that a login page appears on the screen which mentions that the login form is vulnerable to MongoDB Verb Injection vulnerability, as shown below:

Capture the request using Burp Suite proxy and send the request to the intruder. Start regex with characters a,b,c,d,e,f,g,…,z. While checking characters one by one, it can be observed that character f displays a login message:

Observe that the character f displayed a valid user id and password, as shown below:


Now perform brute force using the Sniper attack type on the password field with regex. Send the request to the intruder and click on clear:

Click on Add (Add payload marker) and mark ^f as the payload position for the attack.


Click on ‘Payloads’ and load all characters from a to z, A to Z and 09 and click on the Start Attack button:

Note password field fl where character l content length is 343 and other alphabets length is 263:

Brute force one by one for every character to determine the password of the admin user, as shown below:

Finally, you will obtain the password of the admin user.

Mitigation and Best Practices

●       Use parameterized queries: Use parameterized queries to avoid concatenating user input with your query. This helps prevent attackers from injecting malicious code into your query.

●       Validate user input: Validate all user input to ensure that it contains only expected values and filter all input to remove any characters that are not needed for the application to function. Reject any input that doesn’t conform to the expected format. This helps prevent attackers from injecting malicious code into your query.

●       Implement role-based access control: Limit user access to only the resources they need to perform their job functions. This helps prevent attackers from accessing sensitive data.

●       Use data encryption: Encrypt data stored in your database to prevent attackers from reading sensitive information.

●       Apply the principle of least privilege: Grant permissions to users on a need-to-know basis. This limits the potential damage that an attacker can do if they gain access to a user account.

References and Further Reading





Leave a Reply

Your email address will not be published. Required fields are marked *

Arrange a Callback

    Contact us