# NoSQL Injection
**NoSQL injection** is a type of *injection attack*. Injection attacks occur when maliciously crafted inputs are submitted by an attacker, causing an application to perform an unintended action. In a NoSQL injection attack, untrusted input from the HTTP request or frontend is inserted into command to be run against a NoSQL database insecurely. This allows an attacker to run arbitrary commands on the database, meaning they can steal and manipulate sensitive data, or inject other malicious code that can be used to escalate their attack.
NoSQL databases like MongoDB, Couchbase, Cassandra and HBase relax some constraints traditionally associated with relational databases to achieve allow flexible, scalable storage. Each database engine has a query language or programmatic interface that allows applications to access and manipulate data within the database. These data access operations are usually executed using parameters from an HTTP request. You should make sure to pass these parameters to your database securely, so attackers cannot inject extra statements or change the logic of an existing statement.
## NoSQL Injection in Python
Each of the major NoSQL databases has an SDK that allows you safely update or read data. Most of these SDKs have some sort of binding mechanism – some are illustrated below.
### MongoDB
“`python from pymongo import MongoClientdef update_user_location(email, city, zip): client = MongoClient(MONGO_CONNECTION_STRING) database = client.database users = database.users # Update the city and zip code for the user with a given email address. Make sure # Try to avoid using the low-level command(…) function. If you do, make sure |
### CouchBase
“`python from couchbase.cluster import Cluster from couchbase.auth import PasswordAuthenticatordef update_user_location(email, city, zip): cluster = Cluster(COUCHBASE_CONNECTION_STRING, authenticator=PasswordAuthenticator(COUCHBASE_USERNAME, COUCHBASE_PASSWORD)) bucket = cluster.bucket(‘bucket’) users = bucket.collection(‘users’) # Update the city and zip code for the user with a given email address – assuming that # Couchbase also allows look up of records via the N1QL query language. If you use this |
### Cassandra
“`python from cassandra.cluster import Clusterdef update_user_location(email, city, zip): cluster = Cluster(CASSANDRA_CONNECTION_STRING) session = cluster.connect() # Update the city and zip code for the user with a given email address – using session.execute(prepared, [ city, zip, email ]) |
### Hbase
“`python import happybasedef update_user_location(email, city, zip): connection = happybase.Connection(HBASE_CONNECTION_STRING) table = connection.table(“users”) # Update the city and zip code for the user with a given email address – assuming that |
## CWEs
* [CWE-943](https://cwe.mitre.org/data/definitions/943.html)