# 2.4.1 Introduction to SQL Injection

## Introduction to SQL Injection

**SQL Injection (SQLi)** is an attack method that exploits the injection of SQL commands into a web application's SQL queries. A successful SQLi attack allows a malicious hacker to access and manipulate the backend database of a web application.

Web applications, ranging from complex systems to Content Management Systems (CMSs) and simple personal web pages, often utilize databases like MySQL, SQL Server, Oracle, PostgreSQL, and others to store data, user credentials, or statistics. Structured Query Language (SQL) is employed by entities such as system operators, programmers, applications, and web applications to interact with databases.

SQL, a powerful interpreted language, is used to extract and manipulate data from databases. Web applications embed SQL commands, known as queries, in their server-side code, with connectors serving as middleware between the web application and the database.

Before delving into attack techniques, understanding some SQL basics is essential. This includes knowledge of SQL statement syntax, query execution, union operations, the DISTINCT and ALL operators, and how comments function.

### SQL Statements

SQL allows the selection of constant values, such as:

```sql
SELECT 22, 'string', 0x12, 'another string';
```

Understanding the UNION command is crucial, as it performs a union between two results:

```sql
<SELECT statement> UNION <other SELECT statement>;
```

The DISTINCT operator eliminates duplicate rows, and a UNION statement implies DISTINCT by default. To allow duplicates, the ALL operator can be used:

```sql
<SELECT statement> UNION ALL <other SELECT statement>;
```

Comments in SQL can be denoted by either '#' or '-- '.

Example: The following queries showcase SQL operations on a database with two tables, "Products" and "Accounts."

```sql
SELECT Name, Description FROM Products WHERE ID='1';
SELECT Name, Description FROM Products WHERE Name='Shoes';
SELECT Name, Description FROM Products WHERE ID='3' UNION SELECT Username, Password FROM Accounts;
SELECT Name, Description FROM Products WHERE ID='3' UNION SELECT 'Example', 'Data';
```

### SQL Queries Inside Web Applications

In web applications, SQL queries are executed through the following steps:

1. Connect to the database.
2. Submit the query.
3. Retrieve and use the results in the application logic.

An example PHP code snippet demonstrates the process:

```php
$dbhostname = '1.2.3.4';
$dbuser = 'username';
$dbpassword = 'password';
$dbname = 'database';

$connection = mysqli_connect($dbhostname, $dbpassword, $dbname);
$query = "SELECT Name, Description FROM Products WHERE ID='3' UNION SELECT Username, Password FROM Accounts;";

$results = mysqli_query($connection, $query);
display_results($results);
```

### Vulnerable Dynamic Query

In dynamic query scenarios, queries are often constructed based on user inputs. The following example illustrates a vulnerable dynamic query:

```bash
$id = $_GET['id'];

$connection = mysqli_connect($dbhostname, $dbpassword, $dbname);
$query = "SELECT Name, Description FROM Products WHERE ID='$id';";

$results = mysqli_query($connection, $query);
display_results($results);
```

The previous example shows some code which uses **user supplied input to build a query** (the _id_ parameter of the GET request). The code then submits the query to the database.

Although the code is functionally correct, this behavior is very dangerous, because a malicious user can exploit the query construction to take control of the database interaction.

Let us see how!

The dynamic query:

```
SELECT Name, Description FROM Products WHERE ID='$id';
```

Expects _$id_ values such as:

* `1` => `SELECT Name, Description FROM Products WHERE ID='1';`
* `Example` => `SELECT Name, Description FROM Products WHERE ID='Example';`
* `Itid3` =>`SELECT Name, Description FROM Products WHERE ID='Itid3';` Or any other string.

But what if the attacker crafts a `$id` value which can actually **change** the query? Something like: `' OR 'a'='a` Then the query becomes: `SELECT Name, Description FROM Products WHERE ID='' OR 'a'='a';`

This tells the database to select the items by checking two conditions:

* The id must be empty (`id=''`)
* **OR** an always true condition (`'a'='a'`)

While the first condition is not met, the SQL engine will consider the second condition of the OR. This second condition is crafted as an always true condition.

In other words, this tells the database to select all the items in the _Product_ table!

An attacker could also exploit the UNION command by supplying:

```
UNION SELECT Username, Password FROM Accounts WHERE 'a'='a
```

Thus changing the query to:

```
SELECT Name, Description FROM Products WHERE ID='' UNION SELECT Username, Password FROM Accounts WHERE 'a'='a';
```

This asks the database tot select the items with an **empty** id, thus selecting an empty set, and then to perform a union with all the entries in the _Accounts_ table.

By using some deep knowledge about the database management system in use, an attacker can get access to the entire database just by using a web application.

### **How Dangerous is a SQL Injection**

Before going deeper into the **find and exploit process** of SQL injection vulnerabilities, you should understand where these vulnerabilities can lead when they are successfully exploited.

First, we have to understand that based on the DBMS that the web application is using (MySQL, SQL Server,...), the attacker is capable of performing a number of actions that go much further than the mere manipulation of the database.

An attacker could read the file systems, run OS commands, install shells, access the remote network, and basically own the whole infrastructure.

This is not always the case however, as we will see later, the more powerful the DBMS, the more advanced the SQL is. This increases the capabilities of an attacker after the exploitation.

Keep in mind that accessing a database that stores confidential data (user credentials, SSNs, credit cards, and whatever sensitive information an enterprise, company, or individual may store in a database) is the single most dangerous form of attack on a web application.

Among all the vulnerabilities that may affect web applications, SQL injections are the **first checked by hackers** because of the fact that they produce the most immediate results. Example: An XSS attacks involves some steps, intelligence, and planning for its successful exploitation. An SQL injection vulnerability, once found, is ready to be exploited.

### **SQLi Attack Classification**

There is a great deal of literature about SQLi and there are many different types of classifications, each one based on different aspects such as:

* Scope of the attack
* Exploitation vector
* Source of the attack

In this section we will refer 3 different **injection attacks and exploitation** types:

* **In-band**
* **Error-based**
* **Blind SQL**

These classifications are based on the exploitation method used to carry out the attack. This will help you follow the explanations of the detection and exploitation phases. Now let's see it in detail!

1. **In-band SQL Injection:** This method uses the same channel to inject SQL code as the one used for the web application pages. For instance, in an in-band attack, the penetration tester seeks a way to request desired information directly from the web application.
2. **Error-Based SQL Injection Attack:** In this approach, penetration testers attempt to compel the Database Management System (DBMS) to generate an error message, utilizing this information for data exfiltration. For example, to exploit an error-based injection, the penetration tester must employ advanced DBMS features. Errors may be conveyed through the web application output or alternative means like automated reports or warning emails.
3. **Blind SQL Injection:** In cases where a web application is vulnerable to blind SQL injection, the injected results are not reflected in the output. Here, the penetration tester needs to find an inference method to exploit the vulnerability. For instance, inference exploitation often involves using true/false conditions, allowing the penetration tester to deduce whether a condition is true or false by observing the behavior of the web application.





###
