SQL Injection: Difference between revisions

From Elvis Wiki
(Changed types of sql queries to categories and added the 3 categories aswell as different types of attacks for every category)
No edit summary
 
(14 intermediate revisions by 3 users not shown)
Line 1: Line 1:
== SQL Injection ==  
== SQL Injection ==
 
SQL Injection (SQLi) is a critical vulnerability often present in applications, particularly web applications. It is widely regarded as one of the most severe threats to the security of web platforms. According to the OWASP Top 10 Web Application Security Risks, injection vulnerabilities remained the top threat in 2021. A successful SQL injection exploit can potentially read sensitive data from the database, modify database data, perform database administration operations such as shutting down the Database Management System (DBMS), recover the content of a given file on the DBMS file system, and in some cases, issue commands to the operating system. The core reason for this is usually due to improper or inadequate coding methods. Invalid input, excessive privileges, uncontrolled variable sizes, detailed error messages, unsanitized user input and multiple statements are some of the sources of SQL injection vulnerabilities.
 
== Impacts of SQL Injections ==
 
SQL Injections can affect the main aspects of the CIA triad of security, namely:
 
* Confidentiality
* Integrity
* Authentication
* Availability


SQL Injection is a vulnerability, which can be found in applications, especially web applications. According to the List of OWASP Top 10 Web Application Security Risks Injections are still on top in 2020. SQL Injections - which are a specific type of Injections - are the most common way for attackers to either fetch sensitive data from databases or harm a system in its dependability or even causing non-availablity of the same. Such vulnerabilities become possible when input data is concatenated to SQL queries in conjuction with the absence of data sanitation.
== Functionality ==
== Functionality ==


This vulnerability can only arise when there is a lack of data sanitation. This implies the existence of data input interfaces, whether an input field or a HTTP header field. However when SQL is used in code at application layer it is often concatenated with input data from presentation layer. The combination of unsanitized input and SQL code concatenation with data input is very bad, because this leads to perfect SQL Injections. Input interfaces can be distinguished between:
This vulnerability can only arise when there is a lack of data sanitation. This implies the existence of data input interfaces, whether an input field or an HTTP header field. However, when SQL is used in code at the application layer, it is often concatenated with input data from the presentation layer.


# Userinput can be every field in the User Interface (UI) where a user can input data.  
Input interfaces can be categorized as:
# Cookies can be altered, because they reside on client-side which enables the user to inject malicious code into it.
# User input: Can be every field in the User Interface (UI) where a user can input data.
# HTTP Header are also a type of input which can contain malicious SQL code.
# Cookies: Can be altered, because they reside on client-side which enables the user to inject malicious code into it.
# HTTP Header: Also a type of input which can contain malicious SQL code.


All these entities contain data which is created on the client-side and also can be altered on the same. This is why the first step when any of this data arrives on the server is sanitation and validation. The latter can be partly done already on client-side. Thus, defining HTML attributes, which force user to use specific type or validating with JS, which can be used to apply regular expressions (Regex) on inputs, is essential.
All these entities contain data created on the client-side, which can also be altered there.


=== Direct attack method ===
=== First-Order injection vs. Second-Order injections ===
When input data, therefore malicious SQL code, is directly concatenated to the SQL code in the application tier it is called Direct attack method. This way an authentication of a web-page can be bypassed.


=== Indirect attack method ===
In a First-Order injection attack, a flaw in a vulnerable application allows an attacker to modify the running code immediately by submitting a malicious input.
In contrast to direct attack the indirect attack is when the SQL statement is terminated and arbitrary statements are attached to it. The end is then marked as a comment with using SQL specific commenting syntax, a double dash ''--''.  


Either way the malicious code is executed at the time it is received by the database.  
Second-Order injections involve attackers planting malicious inputs into a system or database, which are exploited when that input is used later. It occurs when user-submitted values are kept in the database without being sanitized and subsequently used by another application functionality.


An attack could look like this:
== Example ==


=== Case 1 ===
[[File:SQLi Example.png|600px|thumb|right|Functional Principle of the Example]]
In the business logic of the application, a query is used to retrieve the data of an user based on username and password. The username and password are filled in by the user via a web form. The input goes directly into the query.
[[File:SQLi_WebIF_Example.png|400px|thumb|right|Web Interface Example]]


SELECT * FROM Users WHERE name ='userName' and password='password';
In the business logic of the application, a query is used to retrieve the data of a user based on username and password. The username and password are filled in by the user via a web form. The input goes directly into the query.


Suppose the attacker gives admin as the username and ' or '1' = '1' as a password. That results in the following query that will be evaluated by the database:
<code>
  SELECT * FROM Users WHERE name ='admin' and password='' or '1'='1';
  SELECT * FROM Users WHERE user ='userName' AND password='password';
</code>


The above SQL query is valid and returns all tuples from the Users relation. By adding the OR condition '1' = '1', the WHERE clause is always evaluated as true. The query then corresponds to:
Suppose the attacker gives  <code>myuser' --</code> as the user and leaves the password empty. That results in the following query that will be evaluated by the database:
SELECT * FROM Users;


<code>
SELECT * FROM Users WHERE user ='myuser' --' AND password='';
</code>


=== Case 2 ===
The <code>--</code> starts a comment in SQL, ignoring everything after it. The query then corresponds to:
Furthermore, several SQL statements can be executed simultaneously on many database servers by separating them with semicolons. The attacker can thus insert additional commands, for example, to delete a relation with a call.


The attacker enters the following in the password field:
  <code>
   
  SELECT * FROM Users = 'myuser';
  ' or '1'='1'; DROP TABLE Users; SELECT * FROM info WHERE '1' = '1
</code>


This results in the following queries:
The SQL Query has successfully been manipulated by an injection.
SELECT * FROM Users WHERE name ='admin' and password=' 'or '1'='1'; DROP TABLE Users; SELECT * FROM info WHERE '1' = '1'


When the database server processes these two queries, it first returns all data records from the Users relation and then deletes or removes the entire Users table.
== Categories of SQLi Attacks ==


== Categories of SQL attacks==
There are a number of SQL injection attacks that occur in different situations. Depending on the target of the attacker, the techniques can be used separately as well as together. Some of these attacks are listed below:
There are a number of SQL injection attacks that occur in different situations.
Depending on the target of the attacker, the techniques can be used separately as well as together.  
First lets take a look at the different categories of SQL attacks:


=== In-Band SQL Injection ===
=== In-Band SQL Injection ===
Most attacks fall under in-band SQL injections. In-band means that the attacker can carry out both attacks and retrieve information via a single communication channel. This means that the results are returned on the same medium as the attack itself was executed.
Most attacks fall under in-band SQL injections. In-band means that the attacker can carry out both attacks and retrieve information via a single communication channel. This means that the results are returned on the same medium as the attack itself was executed.


Known examples for this category would be:
Known examples for this category would be:


==== Tautologies ====
==== Tautology ====
The goal of the Tautologies attack is to find injectable parameters in the application to bypass authentication and initially extract data.
The basic idea here is to always set the where clause in the SQL statement to true so that the condition is ignored. The most common tautology is or 1 = 1. By concatenating the operator or and 1 = 1, another condition is set that is always true, so that the result of the entire condition is true. An example of this can be found in the previous chapter.
 
==== Error Based ====
Error based SQL Injection get their information from error messages. This means that an SQL statement is manipulated in such a way that an error message is thrown by the server. This error message can then be evaluated and thus reveal the type of database and the vulnerability to SQL injections.


==== Union Based ====
In a Tautology SQL injection attack, the attacker tries to utilize a conditional query statement to evaluate it as always true. Furthermore, the attacker uses the "OR" clause to insert and effectively change a condition into a tautology, which is always true. Bypassing authentication, discovering injectable parameters, and extracting data are all examples of this attacking intent.


In the case of a UNION query attack, the keyword 'UNION' is inserted in the input in order to retrieve data from other relations in the database. UNION enables the execution of several independent SQL queries in addition to the main instruction. The results of the further queries are appended to the results of the legitimate SQL query.
An example of this attack is a login form in a website that accepts the user-provided email address, and password, then submits them directly to the backend. The following code is executed against the database:


As a prerequisite, the attacker must have information about the database in order to extract data using UNION. These include e.g. Information about table names and their respective attributes, with which the further queries can be created and linked to the original statement. Furthermore, the individual queries must return the same number of columns and the data types of the attributes must be compatible between the individual queries.
<code>
The attacker can use the ORDER BY clause to derive the number of columns from the results. The clause is added to the statement and the column index is increased until an error message occurs. The columns in a relation can be specified in the ORDER BY clause by an index, so you do not need to know the column names.
SELECT * FROM users WHERE email = $_POST[’email’] AND password = md5($_POST[‘password’]);
</code>


Example of a UNION query attack:
The values of the <code>$_POST[]</code> array are used straight in the above code without being sanitized and the MD5 algorithm is used to encrypt the password. When an attacker enters <code>xy@yahoo.com' OR 1 = 1 --</code> into the email field the following code can be exploited:
SELECT accounts FROM Users WHERE username=''username'' and password=''password''


The attacker extends the legitimate instruction by entering the following in the password field:
<code>
SELECT * FROM users WHERE email = 'xy@yahoo.com' OR 1 = 1 --' AND password = md5('123');
</code>


' 'UNION SELECT cardNo FROM Credit Cards WHERE acctNo=123456 -- ',
* The string quotation is completed with a single quote at the end of xy@yahoo.com.
* <code>OR 1 = 1</code> is a condition that is always true.
* <code>-- AND</code> .... is a SQL comment that removes the password portion from the equation.


This results in the following query:
==== Union-Based SQLi ====


SELECT accounts FROM users WHERE login=' ' UNION SELECT cardNo from CreditCards
In this form of attack, the attacker uses the <code>UNION</code> operator to return records from another table. As a result of this attack, the database produces a dataset that is a union of results of the original query and the injected query. Bypassing authentication and obtaining data are the goals of this attack.
where acctNo=123456


The first statement returns zero. However, the second query is performed and returns the card number from the account number 123456.
An example of a Union query:


=== Blind SQL Injection ===
<code>
Blind SQL injections may not result in an immediate response from the server. The injected commands are processed by the server and do not throw an error message, only the behavior of the server afterwards allows conclusions to be drawn about the execution and results of these, this leads to their nickname "Blind SQL Injections". The big disadvantage of these attack methods is the time required and the reliability.
SELECT * FROM Accounts WHERE user=’’ UNION SELECT *FROM Students—‘AND pass=’’AND eid=
</code>


Two types of Blind SQL Injections exist:
* The result of the first query in the example given above is null and the second one returns all the data in the Students table so the union of these two queries is the student table.


==== Boolean Based ====
==== Error-based SQLi ====
Boolean based means that boolean queries are used to get different answers from the server.
Depending on the answer, you know that there is a certain UserId or a certain user has administrator rights.


For example it is assumed that a website retrieves its user data from the database using a UserId. The ID is transferred via the URL:
Error-based SQLi is an in-band SQL injection technique that uses error messages of the database server to gather information about the structure of the database. An attacker can sometimes enumerate an entire database using only error-based SQL injection. syntax, type conversion, or logical error. While errors are useful during the development phase of a web application, they should be hidden on production or logged to a secure file, therefore no vulnerable/injectable parameters can be revealed to an attacker.
To check whether an SQL injection is possible, the following condition (and 1 = 2) is added.


http://newspaper.com/items.php?id=2 and 1=2
=== Blind SQLi ===


The actual SQL query that is executed is:
An Blind SQLi attack is a technique in which the attacker asks a database a series of questions and then extracts the replies. Following that, the attacker decides on their next line of action based on the responses of the database. Because the attacker has no prior knowledge of the database or the replies that are generated, this is considered a challenging SQLi assault. Identifying injectable parameters, extracting data, and determining database schema are all part of the attacking intent. The Boolean-Based SQLi attack and the Time-Based SQLi attack are two most common types of blind SQLi attacks.


SELECT title, description, body FROM items WHERE ID = 2 and 1=2
==== Boolean-based SQLi ====


In order for this assertion to be confirmed, the attacker builds a condition that returns true. This would be, for example, and 1 = 1, since 1 = 1 is always correct:
In this technique, the information must be inferred from the behavior of the page by asking the server true/false questions. If the injected statement evaluates to true, the page continues to function normally. If the statement evaluates to false, although there is no descriptive error message, the page differs significantly from the normally-functioning page.


http://newspaper.com/items.php?id=2 and 1=1
An example of Boolean-based SQli:


==== Time Based ====
<code>
In time-based attacks, the attacker inserts a query after the actual request, e.g. whether the system username is admin. If yes, the server should wait 15 seconds before returning the answer.
SELECT accounts FROM users WHERE login = ‘user’ and 1=0 -- ‘ AND password=‘ ‘ AND pin = 0
This shows that both boolean based and time based attacks are very good at revealing sensitive information about the server without sending any sensitive data around, because in the end the server responds with a normal user query, only the response times change.
SELECT accounts FROM users WHERE login = ‘user’ and 1=1 -- ‘ AND password=‘ ‘ AND pin = 0
</code>


=== Out-of-Band SQL Injection ===
* 1=0 False
Out-of-band SQL injections use a different information channel than the actual attack vector, hence their name Out-of-band SQL injections. However, these are rarely used nowadays because special functions must be activated on the database server.
* 1=1 True
For example, it must be possible to set up a DNS query or an HTTP request within the SQL query.
A well-known example of out-of-band SQL injections would be a DNS query to a server controlled by the attacker, in which case the information is packaged as a URL and sent to the attacker as a DNS query.


== Prevention ==
==== Time-based SQLi ====
The countermeasures for SQL injection, apart from the type of attack, are mainly the same. The root cause of SQL injections is the lack of input validation. Therefore, the simple solution to address these vulnerabilities is to use appropriate defensive coding. If you are working with user input that is initially used in SQL queries, it should be passed to the query via parameters and validated using defined regular expressions, also known as input whitelisting.


* Check the input type by parameterizing
The Timing attack allows an attacker to gather information from the response time of the database by executing an injected query in the form of an if/then statement and the <code>WAITFOR</code> keyword. This causes a delay along with the branches in the database response for a specific amount of time. The attacker can then determine which branch was chosen in their injection by analyzing the increase or decrease in database response time as well as the answer to the injected question.
* Positive pattern comparison
* Filter input data
* Avoid error messages
* Least privilege
* Cloudflare or other third party services


== Practice ==
In the example the attacker tries to find the first character of the first table by comparing its ASCII value with X. If there is a 9-second delay in the response time, they realize that the answer to this question is true. So by continuing the process the name of the first table can be discovered.


=== Damn Vulnerable Web App (DVWA) ===
An example:
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is damn vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, help web developers better understand the processes of securing web applications and aid teachers/students to teach/learn web application security in a class room environment.


To Install the DvWA project follow the following page:
<code>
SELECT * FROM Accounts WHERE user=’user1’ AND ASCII (SUBSTRING((SELECT TOP 1 name FROM sysobjects),1,1))>X WAITFOR DELAY ‘000:00:09’- -‘AND PASS=’‘ AND eid=
</code>


* https://github.com/ethicalhack3r/DVWA
=== Out-of-band SQLi ===


Installation:
Unlike traditional SQL injections, which rely on the standard communication channels between the attacker and the targets database, out-of-band attacks involve retrieving data through alternative channels. Out-of-band SQL injection typically uses DNS requests, HTTP requests, or other network protocols to transmit data to the attacker's machine. Such is the case with Microsoft SQL Server’s xp_dirtree command, which can be used to make DNS requests to a server an attacker controls; as well as Oracle Database’s UTL_HTTP package, which can be used to send HTTP requests from SQL and PL/SQL to a server an attacker controls.


=== Burp suite ===
== Prevention ==
Burp Suite is a tool for performing penetration testing of web applications. With the Burp Suite, administrators can intercept and manipulate HTTP / HTTPS traffic to web applications before it is sent to the server. This enables security gaps in web applications to be discovered quickly and effectively.
 
To start intercepting web traffic, you have to set the proxy of the browser to 127.0.0.1:8080. The proxy listener is by default configured on 127.0.0.1:8080 in burp suite.
 
[[File:Proxy 4.png]]


Despite the variety of SQL injection attacks, prevention is straightforward and primarily involves better handling of user data. Although certain treatments have drawbacks, they have shown to be helpful in defending. The following are some SQL attack defense strategies.


In the DVWA project move to "SQL Injection" and type in the following input as User ID:
=== Prepared statement ===


1' or 1=1
The prepared statement was created to make SQL more efficient, but it is also provided a better security mechanism. This technique defines all SQL code beforehand and only adds arguments later. Because user-provided parameters are not sent directly to the database, even if the attacker passes a SQL command in the user input, it will not be included in the final SQL statement at runtime. This function inserts a question mark (<code>?</code>) in the query's input field, then uses <code>setString()</code> (in the case of Java programming language) or other methods in other languages to provide the parameter as user input.


This will deliver all users stored in the database as the condition is always true.
<code>
PreparedStatement ps=conn.prepareStatement ("SELECT * FROM users_data WHERE username=? AND password=?");
ps.setString(1, username);
ps.setString(2, password);
resultset = ps.executeQuery();
</code>


[[File:demo2.png]]
A prepared statement can take many different forms and be written in a variety of languages.


Afterwards when switching to burp suite tab "Proxy" -> History you will see that the request has been captured. Within the request the "PHPSESSID" will be included as part of the cookie.
=== Stored procedure ===


[[File:demo3.png]]
Stored procedures prevent SQL injection in the same way as prepared statements do, but the difference is that stored procedures are defined and stored in the database itself by a programmer and after that, they are called by the application. Store procedure sits between application and database, therefore the user is not able to directly read or write from the database. A stored procedure is not always protected from SQL injection, if the developer uses a dynamic query inside it. It is the developer's responsibility to avoid using dynamic queries inside a stored procedure to prevent SQL injection.


With this sessionid it is possible to connect to database and get further information with the help of a third tool called "sqlmap". To get the databases within DBMS system use the following command:
=== Whitelisting/Blacklisting ===


sqlmap -u "http://localhost/DVWA/vulnerabilities/sqli/?id=1&Submit=Submit" "--cookie=security=<e.g. medium>; PHPSESSID=<SessionID>" --dbs
'''Whitelisting''' is the practice of only accepting information that is known to be good. Before accepting the input for further processing, it should be assured that it complies with the expected known values, type, length or size, numeric range, or other format criteria.


[[File:demo4.png]]
When implementing whitelist validation, consider the following:


To retrieve the tables of a specific database for example dvwa database. Replace the "--dbs" option with the "--tables" and "-D" option and define the database.
* '''Known Values:''' Does the input match a predefined set of safe, well-known values? Can its correctness be verified? 
* '''Data Type:''' Is the input of the correct data type? For example, is it a number where expected? 
* '''Data Size:''' Does the input conform to the expected length or size? 
* '''Data Range:''' If a numeric input is required, is it within the acceptable range (e.g., positive vs. negative numbers)? 
* '''Data Content:''' Does the input align with the expected character set or format? For instance, is it restricted to alphanumeric characters? Regular expressions are commonly used to enforce such content validation.


sqlmap -u "http://localhost/DVWA/vulnerabilities/sqli/?id=1&Submit=Submit" "--cookie=security=low; PHPSESSID=t664gnfopfo6kem1nkon3a6kvb" --tables -D dvwa


The inverse of whitelisting is '''blacklisting''', which refers to not allowing characters or words that have been defined in a developer's blacklist. Any input that is listed in the blacklist is automatically eliminated or causes an error. '''Blacklisting''' is generally considered to be less safe than '''whitelisting''' as it only blocks known harmful inputs and may overlook new or unexpected attack vectors.


[[File:demo5.png]]
=== Use the principle of least privilege ===


Furthermore, it is possible to see the database schema from database "dvwa" as well by executing the following command:
The idea of least privilege both avoids SQL injection attacks and mitigates their impact if they do occur. Instead of granting users access to the entire database, this strategy allows them to simply access the tables they require. They should be given only the privileges they require, such as read-only, write-only, or read and write, depending on their needs. The concept of least privilege is a cornerstone of security, and it also applies to SQL injections. As a result, the impact of SQL injection is reduced.


sqlmap -u "http://localhost/DVWA/vulnerabilities/sqli/?id=1&Submit=Submit" "--cookie=security=low; PHPSESSID=t664gnfopfo6kem1nkon3a6kvb" --columns -D dvwa -T users
=== Web Application Firewalls (WAFs) ===


Implementing a firewall can block potential attacks before they reach the web application. The firewall should filter out entries with binary data, escape sequences, and comment characters. Multiple layers of validation can be added and unvalidated user input can be concatenated.


[[File:demo6.png]]
== Detection ==


At the end to get to the sensitive data the attacker will execute the command:
Standard SQL injection Detection Software are Fuzzing tools, dynamic analysis tools and Web Application Firewalls. Nowadays (2024) Machine Learning (ML) and Deep Learning (DL) Detection are coming in handy for IT Security. With ML and DL the Security keeps up to date and less likley expires, when new SQL injection attacks are evolving.
sqlmap -u "http://localhost/DVWA/vulnerabilities/sqli/?id=1&Submit=Submit" "--cookie=security=low; PHPSESSID=t664gnfopfo6kem1nkon3a6kvb" --dump -D dvwa -T users


An example is the Detection with the CNN-BiLSTM Algorithm. Their Detection process looks like this:


[[File:demo7.png]]
[[File:SQLi CNN-BiLSTM.png|500px|SQLi_CNN-BiLSTM]]


== References ==
== References ==


* https://ieeexplore.ieee.org/document/9445347
* https://ieeexplore.ieee.org/document/8880301
* https://ieeexplore.ieee.org/document/10481914
* https://ieeexplore.ieee.org/document/9410675
* https://ieeexplore.ieee.org/document/10250505
* https://ieeexplore.ieee.org/document/6400112
* https://ieeexplore.ieee.org/document/6400112
* https://ieeexplore.ieee.org/abstract/document/6396096
* https://www.researchgate.net/publication/249773840_A_Classification_of_SQL_Injection_Attacks_and_Countermeasures
* https://www.w3.org/Protocols/rfc2616/rfc2616.html
* https://resources.infosecinstitute.com/topic/sql-injection-http-headers
* https://www.researchgate.net/publication/322735440_Detection_and_Prevention_of_SQL_Injection_Vulnerabilities_in_Web_Applications_A_Review
* http://www.gtisc.gatech.edu/bioaucsmith.html
* https://pdfs.semanticscholar.org/81a5/02b52485e52713ccab6d260f15871c2acdcb.pdf/
* https://pdfs.semanticscholar.org/81a5/02b52485e52713ccab6d260f15871c2acdcb.pdf/
* https://ieeexplore.ieee.org/abstract/document/6396096
* http://web.archive.org/web/20210302071805/https://www.dbcybertech.com/pdf/sql-injection-detection-web-environment.pdf
* https://www.dbcybertech.com/pdf/sql-injection-detection-web-environment.pdf
* https://www.cisecurity.org/wp-content/uploads/2017/05/SQL-Injection-White-Paper2.pdf
* https://www.cisecurity.org/wp-content/uploads/2017/05/SQL-Injection-White-Paper2.pdf
* https://info.sucuri.net/hubfs/images/owasp-ebook-2019/sucuri-ebook-OWASP-top-10.pdf
* https://info.sucuri.net/hubfs/images/owasp-ebook-2019/sucuri-ebook-OWASP-top-10.pdf
* http://www.dvwa.co.uk/
* http://web.archive.org/web/20200125164747/http://www.dvwa.co.uk/
* https://owasp.org/www-project-top-ten/
* https://owasp.org/www-project-top-ten/


[[Category:Basic]]
[[Category:Pentesting]]

Latest revision as of 17:46, 18 December 2024

SQL Injection

SQL Injection (SQLi) is a critical vulnerability often present in applications, particularly web applications. It is widely regarded as one of the most severe threats to the security of web platforms. According to the OWASP Top 10 Web Application Security Risks, injection vulnerabilities remained the top threat in 2021. A successful SQL injection exploit can potentially read sensitive data from the database, modify database data, perform database administration operations such as shutting down the Database Management System (DBMS), recover the content of a given file on the DBMS file system, and in some cases, issue commands to the operating system. The core reason for this is usually due to improper or inadequate coding methods. Invalid input, excessive privileges, uncontrolled variable sizes, detailed error messages, unsanitized user input and multiple statements are some of the sources of SQL injection vulnerabilities.

Impacts of SQL Injections

SQL Injections can affect the main aspects of the CIA triad of security, namely:

  • Confidentiality
  • Integrity
  • Authentication
  • Availability

Functionality

This vulnerability can only arise when there is a lack of data sanitation. This implies the existence of data input interfaces, whether an input field or an HTTP header field. However, when SQL is used in code at the application layer, it is often concatenated with input data from the presentation layer.

Input interfaces can be categorized as:

  1. User input: Can be every field in the User Interface (UI) where a user can input data.
  2. Cookies: Can be altered, because they reside on client-side which enables the user to inject malicious code into it.
  3. HTTP Header: Also a type of input which can contain malicious SQL code.

All these entities contain data created on the client-side, which can also be altered there.

First-Order injection vs. Second-Order injections

In a First-Order injection attack, a flaw in a vulnerable application allows an attacker to modify the running code immediately by submitting a malicious input.

Second-Order injections involve attackers planting malicious inputs into a system or database, which are exploited when that input is used later. It occurs when user-submitted values are kept in the database without being sanitized and subsequently used by another application functionality.

Example

Functional Principle of the Example
Web Interface Example

In the business logic of the application, a query is used to retrieve the data of a user based on username and password. The username and password are filled in by the user via a web form. The input goes directly into the query.


SELECT * FROM Users WHERE user ='userName' AND password='password';

Suppose the attacker gives myuser' -- as the user and leaves the password empty. That results in the following query that will be evaluated by the database:


SELECT * FROM Users WHERE user ='myuser' --' AND password=;

The -- starts a comment in SQL, ignoring everything after it. The query then corresponds to:


SELECT * FROM Users = 'myuser';

The SQL Query has successfully been manipulated by an injection.

Categories of SQLi Attacks

There are a number of SQL injection attacks that occur in different situations. Depending on the target of the attacker, the techniques can be used separately as well as together. Some of these attacks are listed below:

In-Band SQL Injection

Most attacks fall under in-band SQL injections. In-band means that the attacker can carry out both attacks and retrieve information via a single communication channel. This means that the results are returned on the same medium as the attack itself was executed.

Known examples for this category would be:

Tautology

In a Tautology SQL injection attack, the attacker tries to utilize a conditional query statement to evaluate it as always true. Furthermore, the attacker uses the "OR" clause to insert and effectively change a condition into a tautology, which is always true. Bypassing authentication, discovering injectable parameters, and extracting data are all examples of this attacking intent.

An example of this attack is a login form in a website that accepts the user-provided email address, and password, then submits them directly to the backend. The following code is executed against the database:


SELECT * FROM users WHERE email = $_POST[’email’] AND password = md5($_POST[‘password’]);

The values of the $_POST[] array are used straight in the above code without being sanitized and the MD5 algorithm is used to encrypt the password. When an attacker enters xy@yahoo.com' OR 1 = 1 -- into the email field the following code can be exploited:


SELECT * FROM users WHERE email = 'xy@yahoo.com' OR 1 = 1 --' AND password = md5('123');

  • The string quotation is completed with a single quote at the end of xy@yahoo.com.
  • OR 1 = 1 is a condition that is always true.
  • -- AND .... is a SQL comment that removes the password portion from the equation.

Union-Based SQLi

In this form of attack, the attacker uses the UNION operator to return records from another table. As a result of this attack, the database produces a dataset that is a union of results of the original query and the injected query. Bypassing authentication and obtaining data are the goals of this attack.

An example of a Union query:


SELECT * FROM Accounts WHERE user=’’ UNION SELECT *FROM Students—‘AND pass=’’AND eid=

  • The result of the first query in the example given above is null and the second one returns all the data in the Students table so the union of these two queries is the student table.

Error-based SQLi

Error-based SQLi is an in-band SQL injection technique that uses error messages of the database server to gather information about the structure of the database. An attacker can sometimes enumerate an entire database using only error-based SQL injection. syntax, type conversion, or logical error. While errors are useful during the development phase of a web application, they should be hidden on production or logged to a secure file, therefore no vulnerable/injectable parameters can be revealed to an attacker.

Blind SQLi

An Blind SQLi attack is a technique in which the attacker asks a database a series of questions and then extracts the replies. Following that, the attacker decides on their next line of action based on the responses of the database. Because the attacker has no prior knowledge of the database or the replies that are generated, this is considered a challenging SQLi assault. Identifying injectable parameters, extracting data, and determining database schema are all part of the attacking intent. The Boolean-Based SQLi attack and the Time-Based SQLi attack are two most common types of blind SQLi attacks.

Boolean-based SQLi

In this technique, the information must be inferred from the behavior of the page by asking the server true/false questions. If the injected statement evaluates to true, the page continues to function normally. If the statement evaluates to false, although there is no descriptive error message, the page differs significantly from the normally-functioning page.

An example of Boolean-based SQli:


SELECT accounts FROM users WHERE login = ‘user’ and 1=0 -- ‘ AND password=‘ ‘ AND pin = 0
SELECT accounts FROM users WHERE login = ‘user’ and 1=1 -- ‘ AND password=‘ ‘ AND pin = 0

  • 1=0 False
  • 1=1 True

Time-based SQLi

The Timing attack allows an attacker to gather information from the response time of the database by executing an injected query in the form of an if/then statement and the WAITFOR keyword. This causes a delay along with the branches in the database response for a specific amount of time. The attacker can then determine which branch was chosen in their injection by analyzing the increase or decrease in database response time as well as the answer to the injected question.

In the example the attacker tries to find the first character of the first table by comparing its ASCII value with X. If there is a 9-second delay in the response time, they realize that the answer to this question is true. So by continuing the process the name of the first table can be discovered.

An example:

SELECT * FROM Accounts WHERE user=’user1’ AND ASCII (SUBSTRING((SELECT TOP 1 name FROM sysobjects),1,1))>X WAITFOR DELAY ‘000:00:09’- -‘AND PASS=’‘ AND eid=

Out-of-band SQLi

Unlike traditional SQL injections, which rely on the standard communication channels between the attacker and the targets database, out-of-band attacks involve retrieving data through alternative channels. Out-of-band SQL injection typically uses DNS requests, HTTP requests, or other network protocols to transmit data to the attacker's machine. Such is the case with Microsoft SQL Server’s xp_dirtree command, which can be used to make DNS requests to a server an attacker controls; as well as Oracle Database’s UTL_HTTP package, which can be used to send HTTP requests from SQL and PL/SQL to a server an attacker controls.

Prevention

Despite the variety of SQL injection attacks, prevention is straightforward and primarily involves better handling of user data. Although certain treatments have drawbacks, they have shown to be helpful in defending. The following are some SQL attack defense strategies.

Prepared statement

The prepared statement was created to make SQL more efficient, but it is also provided a better security mechanism. This technique defines all SQL code beforehand and only adds arguments later. Because user-provided parameters are not sent directly to the database, even if the attacker passes a SQL command in the user input, it will not be included in the final SQL statement at runtime. This function inserts a question mark (?) in the query's input field, then uses setString() (in the case of Java programming language) or other methods in other languages to provide the parameter as user input.


PreparedStatement ps=conn.prepareStatement ("SELECT * FROM users_data WHERE username=? AND password=?");
ps.setString(1, username);
ps.setString(2, password);
resultset = ps.executeQuery();

A prepared statement can take many different forms and be written in a variety of languages.

Stored procedure

Stored procedures prevent SQL injection in the same way as prepared statements do, but the difference is that stored procedures are defined and stored in the database itself by a programmer and after that, they are called by the application. Store procedure sits between application and database, therefore the user is not able to directly read or write from the database. A stored procedure is not always protected from SQL injection, if the developer uses a dynamic query inside it. It is the developer's responsibility to avoid using dynamic queries inside a stored procedure to prevent SQL injection.

Whitelisting/Blacklisting

Whitelisting is the practice of only accepting information that is known to be good. Before accepting the input for further processing, it should be assured that it complies with the expected known values, type, length or size, numeric range, or other format criteria.

When implementing whitelist validation, consider the following:

  • Known Values: Does the input match a predefined set of safe, well-known values? Can its correctness be verified?
  • Data Type: Is the input of the correct data type? For example, is it a number where expected?
  • Data Size: Does the input conform to the expected length or size?
  • Data Range: If a numeric input is required, is it within the acceptable range (e.g., positive vs. negative numbers)?
  • Data Content: Does the input align with the expected character set or format? For instance, is it restricted to alphanumeric characters? Regular expressions are commonly used to enforce such content validation.


The inverse of whitelisting is blacklisting, which refers to not allowing characters or words that have been defined in a developer's blacklist. Any input that is listed in the blacklist is automatically eliminated or causes an error. Blacklisting is generally considered to be less safe than whitelisting as it only blocks known harmful inputs and may overlook new or unexpected attack vectors.

Use the principle of least privilege

The idea of least privilege both avoids SQL injection attacks and mitigates their impact if they do occur. Instead of granting users access to the entire database, this strategy allows them to simply access the tables they require. They should be given only the privileges they require, such as read-only, write-only, or read and write, depending on their needs. The concept of least privilege is a cornerstone of security, and it also applies to SQL injections. As a result, the impact of SQL injection is reduced.

Web Application Firewalls (WAFs)

Implementing a firewall can block potential attacks before they reach the web application. The firewall should filter out entries with binary data, escape sequences, and comment characters. Multiple layers of validation can be added and unvalidated user input can be concatenated.

Detection

Standard SQL injection Detection Software are Fuzzing tools, dynamic analysis tools and Web Application Firewalls. Nowadays (2024) Machine Learning (ML) and Deep Learning (DL) Detection are coming in handy for IT Security. With ML and DL the Security keeps up to date and less likley expires, when new SQL injection attacks are evolving.

An example is the Detection with the CNN-BiLSTM Algorithm. Their Detection process looks like this:

SQLi_CNN-BiLSTM

References