OWASP Top10

What is SQL Injection ? Impact, Prevention and Remediation

What is SQL Injection ?

SQL injection is a type of cyber attack in which an attacker inserts malicious code into an SQL (Structured Query Language) statement in order to manipulate the database that the statement is sent to. This type of attack can be used to gain unauthorized access to sensitive information, modify data, or even destroy data.

How SQL Injection works

  1. Here is a detailed example of how SQL injection works:
  1. The attacker identifies a vulnerable web application that uses SQL queries to interact with its database.
  2. The attacker crafts a malicious SQL query that will be inserted into the web application’s normal SQL queries. For example, the attacker may craft a query that will retrieve sensitive information from the database or modify data in the database.
  3. The attacker then sends the malicious SQL query to the web application, disguised as a legitimate user input. For example, the attacker may enter the malicious SQL query into a search field on the web application.
  4. The web application’s database receives the SQL query, including the malicious code. It then processes the query and executes the malicious code, potentially allowing the attacker to access or modify sensitive data.
  5. The attacker can then use the information gained from the SQL injection attack to gain unauthorized access to the web application or its database, or to cause damage to the web application or its data.

Examples of SQL Injection Vulnerability –

  1. A login form that accepts a username and password from a user, but does not properly sanitize the input before sending it to the database for verification. This could allow an attacker to enter malicious SQL code in the username or password fields, potentially allowing them to access sensitive data or alter the database.
  2. A search form that allows users to search for specific records in the database, but does not validate the input before executing the query. This could allow an attacker to enter malicious SQL code in the search field, potentially allowing them to access sensitive data or alter the database.
  3. A website that allows users to submit comments or reviews, but does not properly sanitize the input before inserting it into the database. This could allow an attacker to enter malicious SQL code in the comment or review fields, potentially allowing them to access sensitive data or alter the database.
  4. A website that displays data from the database on a public page, but does not properly sanitize the input before executing the query. This could allow an attacker to enter malicious SQL code in the URL or form fields, potentially allowing them to access sensitive data or alter the database.

Types of SQL Injections

There are several types of SQL injection attacks, including the following:

1. Union-based SQL injection

This type of injection is used to combine the results of two or more SELECT statements into a single result. For example, a hacker may inject the following code into a login form:

' OR 1=1 UNION SELECT username, password FROM users --

This code would cause the database to combine the results of the original SELECT statement with the results of the SELECT statement that retrieves the username and password from the users table. The result of this injection would be a list of all the username and password combinations in the database.

2. Error-based SQL injection

This type of injection is used to cause the database to return error messages that reveal sensitive information about the structure and contents of the database. For example, a hacker may inject the following code into a search form:

' OR 1=1; DROP TABLE users --

This code would cause the database to drop (delete) the users table, which would result in an error message that reveals the existence and name of the table.

3. Blind SQL injection

This type of injection is used to extract sensitive information from the database without causing any visible error messages. For example, a hacker may inject the following code into a search form:

' OR 1=1 AND (SELECT COUNT(*) FROM users) > 0 --

This code would cause the database to return the number of rows in the users table. If the number is greater than 0, it indicates that the table exists and contains at least one row. The hacker can then use this information to craft additional injections to extract more sensitive information from the database.

4. Time-based SQL injection

This type of injection is used to extract sensitive information from the database by causing the database to delay its response. For example, a hacker may inject the following code into a search form:

' OR 1=1 AND SLEEP(5) --

This code would cause the database to delay its response for 5 seconds. The hacker can then use this delay to determine whether a particular table or column exists in the database.

5. Boolean-based SQL Injection

This type of injection attack relies on the use of a condition (such as true or false) to determine the outcome of a query. This type of injection is often used when an attacker does not have access to the database or does not have the necessary privileges to extract data directly. For example, the attacker is trying to determine whether the username “admin” exists in the database by using a condition in the WHERE clause of the query:

Original query:

SELECT * FROM users WHERE username='admin' AND password='correctpassword';

Injected query:

SELECT * FROM users WHERE username='admin' AND password='incorrectpassword' OR 1=1;

Vulnerable SQL code example

Consider the following code:

String userInput = request.getParameter("userInput");

String query = "SELECT * FROM users WHERE username = '" + userInput + "'";

Statement stmt = connection.createStatement();

ResultSet rs = stmt.executeQuery(query);

In this code, the userInput parameter is passed directly into the SQL query without any validation or sanitization. This makes the code vulnerable to SQL injection attacks.

For example, if a malicious user enters the following input:

' OR 1=1; DROP TABLE users; --

The resulting query will be:

SELECT * FROM users WHERE username = '' OR 1=1; DROP TABLE users; --'

This query will return all the rows in the users table and then drop the table, potentially deleting all the data in the database.

To prevent this vulnerability, the userInput parameter should be validated and sanitized before being included in the query. This can be done by using prepared statements or by escaping special characters in the input.

Impact of SQL Injections

SQL injections can have significant impacts on an organization, including:

1. Loss of sensitive data:

SQL injections allow attackers to access and extract sensitive data, such as customer information, financial records, and intellectual property. This can lead to significant financial and reputational damage to the organization.

2. Disruption of business operations:

SQL injections can allow attackers to manipulate or delete data, which can cause disruptions to business operations and lead to financial losses.

3. Loss of trust and credibility:

Customers and stakeholders may lose trust and confidence in the organization if their data is compromised or if business operations are disrupted. This can lead to loss of customers and revenue, as well as damage to the organization’s reputation.

4. Legal and regulatory penalties:

Depending on the nature and severity of the data breach, the organization may face legal and regulatory penalties, such as fines and penalties for violating privacy laws.

5. Increased security costs:

Organizations may need to invest in additional security measures and tools to prevent and mitigate the effects of SQL injections, which can be costly.

Overall, SQL injections can have a significant negative impact on organizations, including financial losses, disruptions to business operations, and damage to reputation and trust.

Prevention of SQL Injection

To prevent SQL injections, the following best practices should be followed:

1. Use parameterized queries

Instead of concatenating user input with SQL queries, use parameterized queries to prevent malicious user input from being interpreted as part of the SQL query.

2. Use prepared statements

Prepared statements compile the SQL query and the user input separately, so the user input cannot be interpreted as part of the query.

3. Escape special characters

Escape special characters in user input, such as single quotes, double quotes, and backslashes, to prevent them from being interpreted as part of the SQL query.

4. Use a whitelist approach to input validation

Instead of checking user input for malicious content, validate it against a set of expected values to ensure it is safe to use.

5. Limit user privileges

Grant users the minimum privileges necessary to perform their tasks, to prevent unauthorized access to sensitive data or the ability to execute malicious SQL queries.

6. Use a web application firewall

A web application firewall (WAF) can be used to monitor and filter incoming HTTP requests for suspicious or malicious SQL queries, and block them before they can be executed.

7. Regularly update and patch your database and web application

Regularly update and patch your database and web application to ensure that any vulnerabilities or security flaws are fixed, to prevent them from being exploited by attackers.

8. Monitor and log database activity

Monitor and log database activity, such as failed login attempts, SQL query errors, and database access, to identify and investigate potential SQL injection attacks.

Tools for finding SQL Injection

SQLMap

SQLmap is a powerful open-source penetration testing tool that automates the process of detecting and exploiting SQL injection vulnerabilities in web applications. It can be used to test the security of web applications and databases, and to identify and exploit SQL injection vulnerabilities in their underlying SQL statements.

SQLmap can be used to enumerate databases, tables, columns, and data from an SQL injection point, as well as to perform various other operations such as reading and writing files, executing commands, and even pivoting to other hosts on the network. It supports various database management systems (DBMS), including MySQL, Oracle, and Microsoft SQL Server, and can be run on various platforms including Linux, Windows, and MacOS.

SQLmap also offers a variety of features and options to customize and fine-tune the attack, such as the ability to use custom payloads and evasion techniques, and to use different injection techniques and methods to bypass security measures. It also provides a comprehensive and user-friendly user interface, as well as detailed logs and reports of the attack results.

How to test SQL Injection vulnerability with SQLMap

  1. Install sqlmap on your system by following the instructions on the sqlmap website (https://github.com/sqlmapproject/sqlmap/wiki/Installation).
  2. Identify the URL of the target website that you want to test for SQL injection vulnerability.
  3. Open a terminal or command prompt and navigate to the directory where sqlmap is installed.
  4. Run the following command to test for SQL injection vulnerability:
./sqlmap -u <target_url> -p <parameter> --dbs

Replace <target_url> with the URL of the target website, and <parameter> with the parameter that you want to test for vulnerability (e.g. “user” or “password”).

  1. The sqlmap tool will then attempt to exploit any vulnerabilities in the target website and display a list of available databases if successful.
  2. To further test the vulnerability, you can use other sqlmap commands, such as “–tables” to list the tables within a specific database, or “–dump” to extract data from a specific table.
  3. Once you have finished testing, you can use the “–cleanup” command to remove any changes made by sqlmap.

How to test SQL Injection with Burpsuite Manually

  1. Open Burp Suite and navigate to the Proxy tab.
  2. Set your browser to use Burp Suite as its proxy and visit the website you want to test for SQL injection vulnerability.
  3. In the Proxy tab, locate the request for the page you are testing and right-click on it. Select “Send to Intruder.”
  4. In the Intruder tab, select the “Positions” tab and select the parameter you want to test for SQL injection vulnerability.
  5. In the “Payloads” tab, add a list of payloads that can be used to test for SQL injection vulnerability. This can include common SQL injection strings such as “1′ OR ‘1’=’1” or “‘ OR 1=1 –“.
  6. In the “Attack” tab, select the “Start attack” button to begin the SQL injection test.
  7. Observe the results of the attack in the “Results” tab. If any of the payloads were successful in injecting SQL into the database, it will be displayed here.
  8. If any vulnerabilities are found, it is important to address them immediately to prevent potential security breaches.

SQL Injection FAQ (Frequently Asked Questions) 

What is SQL injection vulnerability?

SQL injection vulnerability is a security vulnerability in a website or web application that allows attackers to inject malicious SQL code into the database, allowing them to access sensitive information or manipulate the data.

How does SQL injection vulnerability occur?

What are the risks associated with SQL injection vulnerability?

How can SQL injection vulnerability be prevented?

What are some common methods used to exploit SQL injection vulnerabilities?

Akshay Sharma

Inner Cosmos

Leave a Reply