Mongodb Nosql Injection Cheat Sheet



Cheat

PDF MongoDB - Cheat Sheet - Blog, MongoDB - Cheat Sheet. Version 1.0 / 27th December 2012 / Page 1 of 4. More information can be found from the MongoDB Tutorial. MongoDB Cheat Sheet e-book: Simplifying Big Data with Streamlined Workflows As part of our MongoDB Guide, we’ve compiled this cheat sheet of common and not-so-common MongoDB commands. NoSQL: A term used for databases which are not traditional SQL systems and may have different query languages and data storage models. An example is MongoDB, which has a query language based on JavaScript. Further Reading: Server-Side Injection in JavaScript whitepaper; Server-Side Injection in non-JS apps; Code Injection; SQL Injection from OWASP.

Infrastructure Pentesting: Databases

Databases store a lot of important information that businesses do not want to be accessed by unauthorized personal. There are also a lot of different database types that a cyber professional needs to be able to understand.

MongoDB

MongoDB is a ‘schema-less’ document based, NoSQL database. It’s ability to scale and manage big data makes Mongo a popular choice for lot of companies. Mongodb stores data in the form of JSON.

Mongodb nosql injection cheat sheet pdf

Mongodb Nosql Injection Cheat Sheet Download

Databases, Collections & Documents
Mongo databases are made up of collections and documents; comparing this with MySQL, these would be tables and rows. MongoDB stores data records as BSON documents, these are binary versions of JSON documents. The maximum BSON document size is 16 megabytes.
Mongo stores data documents in collections. There can be many documents within a collection.
Every document must always contain an _Objectid. A unique identifier for the document. Mongo will automatically create an object ID records if it is not specified. This objectID is a 12 byte string that consists of:

    • a 4-byte value representing the seconds since the Unix epoch,
    • a 5-byte random value, and
  • a 3-byte counter, starting with a random value.

It can also contain information such as the timestamp of the document and much more.

Basic Syntax

Basic mongodb query/method syntax is in the format of db.parameter.option. There are some similarities between mongo and mysql, for example:

  • Selecting records from the customer table:

MySQL: SELECT * FROM customer

MongoDB: db.customer.find()

Nosql Tutorial

  • Inserting records into the customer table

MySQL: INSERT INTO customer (cust_id, branch, status) VALUES (‘appl01’, ‘main’, ‘A’)

MongoDB: db.customer.insert({ cust_id: ‘appl01’, branch: ‘main’, status: ‘A’ })

Mongo Shell Common Commands

Below is a list of basic commands to help navigate your way through a NoSQL database.

    • show dbs – this command will list all the active available databases in Mongo
    • use [DATABASE NAME] – this command is used to select and use a specified database from the list of databases (For a database to be listed it must contain one document.)
Injection
    • show collections – this will list all the collections in the selected database
    • db.[DATABASE NAME].insert({}) – Enter a record within a collection, (Worth noting that Mongo will create the collection with this command, if it doesn’t already exist).
    • db.[COLLECTION NAME].find() – This command will output all the documents within a specified collection. #
  • ObjectId(“123”).getTimestamp() – To get timestamp of a document in a collection

SQL:

An Introduction

Structured Query Language
SQL acts a middle man between a database and website, however there are a few variations of SQL which are suited to different database needs. Three of the most popular are: SQLite, MySQL, and PostgreSQL.

Common SQL commands

SELECT – This statement is used to fetch data from the database, therefore every database query will start with SELECT.
*– The asterisk represents all (wild card), therefore SELECT * would translate to ‘select all’.
FROM – selects a table within the database, from which the data is queried.
WHERE – specifies which column you wish to perform your SQL command in.
LIKE – This statement will be used in conjunction with the WHERE statement to search each row for a specific pattern.
BETWEEN– used to filter data between two values.
ORDER BY (ASC | DESC) – This statement is used to order the returned rows from the SQL command.
As an example, SELECT * FROM table WHERE name LIKE ‘Bob’ would return all rows from the table where the name of a user is Bob.

Examples:

Getting employees from the “employees table”:
select * from employees

Getting employees from the “employees table” that earn between a certain amount
select * from employees where pay between ‘54000’ AND ‘63000’

Getting an employees email:
select * from employees where email like “First.SecondName@email.com”

Sorting the table:
select * from employees where pay ORDER BY pay

Sheet

How to Defend Against it

Primary Defenses:

  • Option 1: Use of Prepared Statements (with Parameterized Queries)
  • Option 2: Use of Stored Procedures
  • Option 3: White List Input Validation
  • Option 4: Escaping All User Supplied Input

Additional Defenses:

  • Also: Enforcing Least Privilege
  • Also: Performing White List Input Validation as a Secondary Defense

SQLMap

sqlmap is a tool used to automate the detection and exploitation of SQL injection flaws, enabling users to carry out tasks such as dumping a database, accessing the underlying file system, and executing commands.

Fetch Website:
sqlmap -u [URL_OR_IP]
*Can’t simply be: www.website.com, has to be for example: http://ww.website.com/index.php….

Fetch website databases/tables/columns:
sqlmap -u [URL_OR_IP] –dbs
–dbs = database
–tables = tables
–columns = columns

To specify the columns:
sqlmap -u [URL_OR_IP] –columns -D corporate_database

Optimise the performance of sqlm:
-o

To provide detailed information about the DBMS:
-f

If you’re an application developer, DBA, or any flavor of technologist, really, code injection should be on your radar.

You have a secure cloud environment. You have database access locked down. But what about your application code? Although it’s considered more secure, the “No” in NoSQLi does not mean un-injectable! NoSQL can be just as susceptible to code injection as any other database code. Not guarding against code injection is like having a security system in place for your doors and leaving a back window open.

What is code injection?

Code injection is simply unvalidated data being added (“injected”) into a vulnerable program where it’s executed as application code, often to disastrous results.

SQLi is one of the most common types of injection and, at over a decade old, is still going strong. Injection issues aren’t limited to just database languages: Beyond SQL and NoSQL, injection can occur in XPath, XML Parsers, SMTP headers, and a wide variety of other contexts. And as far as severity goes, code injection is a cousin to RCE (remote code execution) — the “Game Over” screen of penetration testing.

That’s why it’s important to detect and prevent NoSQLi in your own applications. Allowing an unmitigated injection vector can threaten the safety of your user base, representing a possible business-ending loss of trust. Fortunately, once you understand the mechanics, there are simple, concrete steps you can take to both detect and prevent NoSQLi vulnerabilities in your own services.

Simple NoSQLi Examples

Typically, MongoDB ingests BSON data (Binary JSON) constructed using a secure BSON query construction tool. But in certain cases, MongoDB can also accept unserialized JSON and Javascript expressions — like in the case of the $where operator.

As with SQL, the $where operator is ripe for abuse and potential injection in NoSQL. However, unlike in SQL, the NoSQL $where expresses its conditional in Javascript. This means it can use the full expressive power of JS to craft possible injection queries instead of being limited to what SQL provides.

Going through lists of MongoDB injection strings in public repos like this one illustrates some of the common injection strategies, which parallel similar vulnerabilities in SQL and other languages.

Nosql Vs Sql

For example, some use the classic 1 1 expression to force a query to return a truthy value in an attempt to read hidden (or admin-level) resources and privileges:

Other snippets emulate a blind injection strategy by using the sleep() function to slow the DB down and create a side-effect that — when used in conjunction with craftily-designed filters — can enumerate oftentimes sensitive information:

And then of course there’s plain old data exfiltration, where the injected query is trying to match and retrieve critical information directly (and not through a programmatic game of “Guess Who”).

After the first example, the remaining two don’t use the $where operator, proving that you don’t need a handy Javascript-flavored expression as a foothold to attack a NoSQL DB.

Preventing NoSQLi

There are several general strategies to pursue when trying to build a NoSQLi-resistant application architecture. It’s no surprise that they conform with general anti-injection advice.

MongoDB / NoSQLi is not special

There’s a weird school of thought where people see injection as being SQL-specific and don’t understand the validity of injection principles applied to other contexts. Hopefully this post convinces you that NoSQLi is real. There’s a reason people write posts with titles like “MongoDB will not prevent NoSQL injections in your Node.js app”

Do not trust unvalidated user data

Don’t trust users! Ever! Even a bit!

This is a truism to the point of being a cliche in security, but expect every input to be probed with malicious intent. To borrow from our $where example earlier, it illustrates pretty clearly why we can’t do something along the lines of $where: unvalidated_input — even if we only think we’re exposing the filter to the user at this point (bad enough!) the fact that users are introducing unvalidated data into the larger query is a total no-no.

Be wary of language/integration specifics

Even though NoSQLi isn’t special when it comes to being immune to injection (and in fact suffers from many of the same types of attacks), that doesn’t mean there aren’t also strategies unique to NoSQLi — or even to the languages / components built on top of a NoSQL DB. A prominent example is that since $where is formatted in a way that passes as a PHP variable, a NoSQL DB built on top of a PHP application has to account for this and the possible scenario of a malicious string injection stored in $where.

Conclusion

Again, the “No” in NoSQLi does not mean un-injectable! NoSQL — similar to SQL, SMTP headers, XML, and a million other contexts — is just as susceptible to code injection and the general treating-things-as-application-code-that-aren’t-application-code pitfalls that plague so many other technologies.

Hopefully though, with this post, you’ve gained a greater understanding of NoSQLi, what it means to your business. Now, you can steer your code to processes that make it less prevalent, less widespread, and less impactful. If you need some MongoDB management advice to make sure your app and hosting environment is secure, ObjectRocket has experienced DBAs who can help.

If you’d like to read more of Joe’s writing on security, code injection, or penetration testing, check out his new guide, Hands-On Bug Hunting for Penetration Testers. You can follow him at joecmarshall.com