SQL & No-SQL injections.
Tags: sql, nosql, cybersecurity, sqlinjections
Published: 2023-08-20 05:44:46

> Whats an SQL Injection?

An SQL Injection attack involves the insertion or injection of a SQL query through input data from the client to a backend server. A successful SQL injection exploit can enable the reading of sensitive data from the database, altering database data (Insert/Update/Delete), executing administrative operations on the database (such as shutting down the DBMS), retrieving the contents of a specific file within the DBMS file system, and, in some cases, issuing commands to the operating system. SQL injection attacks are a type of injection attack, where SQL commands are inserted into data-plane inputs to manipulate the execution of predefined SQL commands.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/x1ipqkvxr7b8md7behjz.png)

**_Difference between SQL vs No-SQL Attacks_**

SQL is a standardized language employed to access and manipulate databases, creating customizable data views for individual users. SQL queries execute commands like data retrieval, updates, and record removal, utilizing various SQL components for these functions. SQL attacks refer to SQL injections targeting databases associated with SQL, such as MySQL, PostgreSQL, Oracle, MS SQL, MariaDB, and others.

NoSQL databases, on the other hand, encompass a variety of database systems like MongoDB, DynamoDB etc that store and retrieve data without using a traditional SQL-based relational model. NoSQL attacks are specifically directed at these types of databases, exploiting vulnerabilities within their unique structures and characteristics.

##Type of SQL attacks

- **Boolean-based SQLI :** This type of SQL attack involves sending a SQL query to the database that prompts the application to return a result. Attackers can exploit vulnerabilities in the application’s response to infer information.

- **Time-based SQLI :** In this scenario, the attacker sends a SQL query to the database, causing it to introduce a delay (for a specific period in seconds) before responding. By observing the delay in the response, the attacker can deduce certain information from the timing.

NoSQL Injection is a security vulnerability that affects web applications utilizing a NoSQL database. NoSQL (Not Only SQL) databases are characterized by their use of flexible data formats and lack of support for Structured Query Language (SQL). These databases typically manage data as key-value pairs, documents, or data graphs. Examples of such databases include MongoDB, OrientDB, DynamoDB (AWS), Redis, and others.


**A Normal Backend Interaction — SQL Databases
(How SQL injections work)**

When prompted by an application, a user enters:

username: _JohnDoe_

password: _password_

The application processes the input:

```
username = getRequestString("username")
password = getRequestString("userpassword")
```
```
sql = 'SELECT * FROM Users WHERE name ="' + username + '" AND pass = "' + password + '"'
```

It translates to the SQL Query:
```
SELECT * FROM users WHERE name = "JohnDoe" AND pass = "password"
```

But in the case of SQL Attacks...
An attacker can:  
**1. Retrieving an Entire Table**

A malicious individual could gain access to usernames and passwords within a database.

A user enters:

username: " OR ""="

password: " OR ""="

Query becomes:

```
SELECT * FROM users WHERE name = "" OR ""="" AND pass = "" OR ""=""
```
_This SQL statement will retrieve all rows from the users table, as the condition OR ""="" always evaluates to true._


**2. Delete a Table Using a Batched SQL Statements**

A malicious individual could delete an entire table from a database.

A user enters:

username: _nuclearfusion; DROP TABLE Suppliers_

password: _password_

Query becomes:

```
SELECT * FROM users WHERE username = "nuclearfusion"; DROP TABLE stockPortfolio;
```


###Preventing SQL Injection Attacks
**Several common methods can help prevent SQL injection attacks:**

1. Avoid allowing multiple statements. For instance:

```
const connection = await mysql.createConnection({
  uri: process.env.DATABASE_URL,
  multipleStatements: false
})
```

2. Employ prepared statements or placeholders instead of variable interpolation. This involves using a _question mark “?”_ in place of the actual value.

3. Validate user input rigorously.

4. Implement allow-lists for user input.

5. Choose databases with restricted user access.

6. Utilize an ORM (Object Relational Mapping) system, such as Sequelize, Knex.js, Hibernate for Spring JPA frameworks, and others. ORMs provide a way to align programming code with database structures, making it easier to interact with databases while also reducing the likelihood of vulnerabilities like injection attacks.


###Preventing No-SQL Injection Attacks:
1. Avoid Directly Passing Request Objects to ODM or ORM Functions.

One of the worst practices is passing something like req.body or req.query directly to our ODM/ORM functions like this:

```
const user = await collection.findOne(req.body); // Bad Practice
```
At the very least, we should use specific fields such as req.body.id

This helps mitigate the risk of NoSQL injection attacks.

```
const user = await collection.findOne({ userId: req.body.id });
```

2. Use input validations like _Zod_, _Yup_ or _express validator_.

3. Sanitize User Inputs and Filters.

4. Utilize the latest versions of technologies and database drivers.



###Conclusion
To learn more about SQL and No-SQL injections, how to detect them and prevent them, click the [original link] (https://medium.com/@elvis.osujic/good-practices-to-prevent-security-vulnerabilities-on-your-backend-servers-pt-1-8bcb6c5122f1) published on medium by me.
and check out the GitHub repo for Injections [here](https://github.com/BigVeezus/SQL-NoSQL-Injection)
Thank you.