Data sanitization against NoSQL query injection in MongoDB and Node.js application
Tags: mongodb, node, javascript, express
Published: 2020-07-22 00:02:00

### Introduction

Any software application that accepts user input data has a cancer at its core called injection attacks. As a result of inadequate input sanitation of data before sending it to the database, this risky vulnerability appears in a range of different applications. The NoSQL paradigm is not an exception. The consequent effect of such an act permits or makes room for a variety of databases to be subject to injection attacks, the most hazardous type of software fault.

Any developer must safeguard against injection attacks in order to stop hostile actors from accessing and changing sensitive data, such as passwords, usernames, email addresses, authentication tokens, and other data. 

### What is a NoSQL database?

Literature claims that the term NoSQL, which stands for "Not Only SQL," was first used in 1998. NoSQL is a cutting-edge database design that supports a wide range of data formats and offers excellent backend support for big data applications.

According to **Dr. Patrick Obilikwu** in his lecture note on **Database Management Systems II**, NoSQL databases are characterized by horizontal scalability, schema-free data models, simple cloud deployment, and are built on the scale-out architecture and fault tolerance. The emergence and subsequent exponential expansion of big data applications is the driving force behind a wide range of paradigms, not just the SQL paradigm.

NoSQL databases are highly appropriate for:

- Big Data capability
- Fast performance 
- Easy replication 
- High scalability
- High availability

### NoSQL injection

Since NoSQL databases like MongoDB still run queries based on user input data, they are still susceptible to injection attacks if the input data is not properly sanitized. The syntax is the primary distinction between SQL and NoSQL injection attacks.

Let's pretend that a NoSQL query injection will let us to enter into the application with a given password even though we don't know the user's **username**. Since the request content is encoded as JSON, we will enter the simulated injection query as our username rather than supplying a valid username. -

```javascript
{
  "username": {"$gt":""},
  "password": "$#@Call4Code"
}
``` 
The aforementioned code snippet illustrated how NoSQL injection queries can be used to attack an application built with MongoDB as the database backend support and Node.JS. You'll be surprised to learn that the code above will work because the query is always evaluating to true.

### Protecting against the NoSQL injection

Using the [**npm** package named **express-mongo-sanitize**](https://www.npmjs.com/package/express-mongo-sanitize) we can easily defend ourselves against this harmful attack. It significantly aids in mitigating and preventing this harmful malicious attack on our database.

### Installation 
> npm install express-mongo-sanitize

### Usage
```javascript
const express = require('express');
const mongoSanitize = require('express-mongo-sanitize');

const app = express();

/*
** IMPORT ROUTES
*/
const userRouter = require('./api/routes/userRoutes');
const postRouter = require('./api/routes/postRoutes');

/*
** GLOBAL MIDDLEWARES
*/
app.use(express.json());
// Data sanitization against NoSQL query injection
app.use(mongoSanitize()); 

/*
** ROUTES
*/
app.use('/api/v1/users', userRouter);
app.use('/api/v1/posts', postRouter);

/*
** HANDLING UNHANDLED ROUTES
*/
app.all('*', (req, res, next) => {
	next(new AppError(`Can't find ${req.originalUrl} on this Server!`, 404));
});

/*
** GLOBAL ERROR
*/
app.use(globalErrorHandler);

module.exports = app;
```
When we look at the request body, request parameters, and request query strings to remove the dollar (**$**) signs and dots (**.**) accordingly before performing the queries, the **mongoSanitize** function, which we have called, produces a middleware function that we can utilize to avoid the attack.