DEV Community

Cover image for SQL & No-SQL injections.
Elvis O.
Elvis O.

Posted on • Updated on • Originally published at Medium

SQL & No-SQL injections.

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

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")
Enter fullscreen mode Exit fullscreen mode
sql = 'SELECT * FROM Users WHERE name ="' + username + '" AND pass = "' + password + '"'
Enter fullscreen mode Exit fullscreen mode

It translates to the SQL Query:

SELECT * FROM users WHERE name = "JohnDoe" AND pass = "password"
Enter fullscreen mode Exit fullscreen mode

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 ""=""
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

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
})
Enter fullscreen mode Exit fullscreen mode
  1. Employ prepared statements or placeholders instead of variable interpolation. This involves using a question mark “?” in place of the actual value.

  2. Validate user input rigorously.

  3. Implement allow-lists for user input.

  4. Choose databases with restricted user access.

  5. 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
Enter fullscreen mode Exit fullscreen mode

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 });
Enter fullscreen mode Exit fullscreen mode
  1. Use input validations like Zod, Yup or express validator.

  2. Sanitize User Inputs and Filters.

  3. 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 published on medium by me.
and check out the GitHub repo for Injections here
Thank you.

Top comments (0)