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.

safecheck.py

Python · 37,975 bytes
#nice for blue team :o, if wnt interaftiveshell etc. go exploit.py, only ethical&bsafety uses <3

import os
import re
import sys
import json
import csv
import time
import socket
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

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 Exposure Scanner
{rst}{yellow}{bold}                         CVSS 9.3 (Critical)
{rst}{red}{bold}══════════════════════════════════════════════════════════════════════════════════════
{rst}{magenta}{bold}             only etchl & legal uses :h, for blue team
{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 (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/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 (Windows NT 10.0; Win64; x64; rv:122.0) Gecko/20100101 Firefox/122.0",
    "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; 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 (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) 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",
]

products = {
    "jira": {
        "marker": "com.atlassian.jira.web.ServletContextProviderListener",
        "probe_path": "/rest/api/2/serverInfo",
        "version_field": "version",
        "fixed_versions": ["9.12.40", "10.3.26", "11.3.12"],
        "label": "Jira Data Center",
    },
    "jira_sm": {
        "marker": "com.atlassian.jira.web.ServletContextProviderListener",
        "probe_path": "/rest/api/2/serverInfo",
        "version_field": "version",
        "fixed_versions": ["5.12.40", "10.3.26", "11.3.12"],
        "label": "Jira Service Management Data Center",
    },
    "confluence": {
        "marker": "com.atlassian.confluence.impl.webapp.ServletsInitializer",
        "probe_path": "/rest/api/serverInformation",
        "version_field": "version",
        "fixed_versions": ["9.2.26", "10.2.19"],
        "label": "Confluence Data Center",
    },
    "bitbucket": {
        "marker": "com.atlassian.plugin.servlet.ResourceDownloadUtils",
        "probe_path": "/rest/api/1.0/application-properties",
        "version_field": "version",
        "fixed_versions": ["9.4.26", "10.2.8", "10.5.1"],
        "label": "Bitbucket Data Center",
    },
    "bamboo": {
        "marker": "com.atlassian.bamboo",
        "probe_path": "/rest/api/latest/info",
        "version_field": "version",
        "fixed_versions": ["10.2.24", "12.1.12"],
        "label": "Bamboo Data Center",
    },
    "crowd": {
        "marker": "com.atlassian.crowd",
        "probe_path": "/crowd/rest/usermanagement/latest",
        "version_field": "version",
        "fixed_versions": ["6.3.7", "7.0.3", "7.1.7", "7.2.4"],
        "label": "Crowd Data Center",
    },
    "crucible": {
        "marker": "com.atlassian.crucible",
        "probe_path": "/rest-service/info",
        "version_field": "version",
        "fixed_versions": ["4.9.15"],
        "label": "Crucible",
    },
    "fisheye": {
        "marker": "com.atlassian.fisheye",
        "probe_path": "/rest-service/info",
        "version_field": "version",
        "fixed_versions": ["4.9.15"],
        "label": "Fisheye",
    },
}

server_headers = [
    "Server",
    "X-Atlassian-Data-Center",
    "X-Confluence-Request-Time",
    "X-AUSERNAME",
    "X-Seraph-LoginReason",
    "X-Powered-By",
]

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

waf_headers = [
    "cf-ray", "cf-cache-status", "x-sucuri-id", "x-sucuri-cache",
    "x-waf", "x-blocked", "x-mod-security", "x-firewall",
    "x-amzn-requestid", "x-amz-cf-id", "x-akamai-transformed",
]

DNS_CACHE_MAX = 10000

log = logging.getLogger("safechecker")
log.setLevel(logging.DEBUG)
log.propagate = False
_stream = logging.StreamHandler(sys.stdout)
_stream.setFormatter(logging.Formatter("%(message)s"))
log.addHandler(_stream)
try:
    _file = RotatingFileHandler("safechecker.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()

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 alert(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 semver(text):
    if not text:
        return None
    m = re.search(r"(\d+)\.(\d+)(?:\.(\d+))?", str(text))
    if not m:
        return None
    return (int(m.group(1)), int(m.group(2)), int(m.group(3) or 0))

def is_vuln(version_tuple, fixed_versions):
    if not version_tuple:
        return None
    for fixed in fixed_versions:
        f = semver(fixed)
        if f and version_tuple < f:
            return True
    return False

def fix_for(version_tuple, fixed_versions):
    if not version_tuple:
        return None
    candidates = []
    for fixed in fixed_versions:
        f = semver(fixed)
        if f and version_tuple < f:
            candidates.append(f)
    if not candidates:
        return None
    return ".".join(str(x) for x in min(candidates))

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"

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 Pool:
    def __init__(self, size=64):
        self._sem = threading.BoundedSemaphore(size)
        self._live = set()
        self._lock = threading.Lock()

    def acquire(self, timeout=10.0):
        if not self._sem.acquire(timeout=timeout):
            raise TimeoutError("connection pool exhausted")
        return True

    def release(self):
        try:
            self._sem.release()
        except ValueError:
            pass

    def track(self, sock):
        if sock is None:
            return
        with self._lock:
            self._live.add(sock)

    def untrack(self, sock):
        if sock is None:
            return False
        with self._lock:
            if sock in self._live:
                self._live.discard(sock)
                return True
            return False

    def shutdown(self):
        with self._lock:
            socks = list(self._live)
            self._live.clear()
        for s in socks:
            try:
                s.close()
            except Exception:
                pass

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
pool = None
throttle = None

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 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
    tracked = False
    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)
        if pool is not None and conn.sock is not None:
            pool.track(conn.sock)
            tracked = True
        headers = {
            "User-Agent": next_ua(),
            "Accept": "application/json, text/plain, */*",
            "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:
            if tracked and pool is not None:
                try:
                    pool.untrack(conn.sock)
                except Exception:
                    pass
            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 check_headers(headers):
    indicators = []
    for h in server_headers:
        if h in headers:
            indicators.append(f"{h}: {headers[h]}")
    server = headers.get("Server", "")
    if "atlassian" in server.lower() or "tomcat" in server.lower():
        indicators.append(f"Server fingerprint: {server}")
    return indicators

def detect_waf(headers):
    detected = []
    header_lower = {k.lower(): v for k, v in headers.items()}
    for h in waf_headers:
        if h.lower() in header_lower:
            detected.append(f"{h}: {header_lower[h.lower()]}")
    if "cf-ray" in header_lower:
        detected.append("Cloudflare WAF")
    if "x-sucuri-id" in header_lower:
        detected.append("Sucuri WAF")
    if "x-amzn-requestid" in header_lower or "x-amz-cf-id" in header_lower:
        detected.append("AWS WAF/CloudFront")
    return detected

def probe_single_product(target, key, timeout, retries, proxy_url=None):
    info = products.get(key)
    if not info:
        return None
    probe_path = info.get("probe_path")
    if not probe_path:
        return None
    try:
        status, headers, body = fetch_with_retry(target, probe_path, timeout, retries, proxy_url)
        if status in waf_status_codes:
            dbg(f"{key} probe -> WAF block ({status})")
            return (key, None, None, status, headers)
        if status == 200 and body:
            try:
                data = json.loads(body)
                version = data.get(info.get("version_field", "version"))
                if version:
                    return (key, version, data, status, headers)
            except (json.JSONDecodeError, ValueError):
                pass
        return (key, None, None, status, headers)
    except Exception as exc:
        dbg(f"{key} probe failed: {exc}")
        return None

def probe_serverinfo(target, timeout, retries, proxy_url=None):
    results = []
    keys = list(products.keys())
    with ThreadPoolExecutor(max_workers=len(keys)) as tpool:
        futures = {tpool.submit(probe_single_product, target, k, timeout, retries, proxy_url): k for k in keys}
        try:
            for fut in as_completed(futures):
                try:
                    result = fut.result()
                except Exception as exc:
                    dbg(f"probe task error: {exc}")
                    continue
                if result:
                    key, version, data, status, headers = result
                    if version:
                        results.append((key, version, data, status, headers))
        except KeyboardInterrupt:
            for f in futures:
                f.cancel()
    return results

def probe_marker_product(target, key, timeout, retries, proxy_url=None):
    info = products.get(key)
    if not info:
        return None
    marker = info.get("marker")
    if not marker:
        return None
    probe_path = "/"
    try:
        status, headers, body = fetch_with_retry(target, probe_path, timeout, retries, proxy_url)
        if status in waf_status_codes:
            dbg(f"{key} marker probe -> WAF block ({status})")
            return (key, None, status, headers)
        if body:
            text = body.decode("utf-8", "replace") if isinstance(body, bytes) else body
            if marker in text:
                return (key, None, status, headers)
        return (key, None, status, headers)
    except Exception as exc:
        dbg(f"{key} marker probe failed: {exc}")
        return None

def detect_product_marker(target, timeout, retries, proxy_url=None):
    results = []
    keys = list(products.keys())
    with ThreadPoolExecutor(max_workers=len(keys)) as tpool:
        futures = {tpool.submit(probe_marker_product, target, k, timeout, retries, proxy_url): k for k in keys}
        try:
            for fut in as_completed(futures):
                try:
                    result = fut.result()
                except Exception as exc:
                    dbg(f"marker probe task error: {exc}")
                    continue
                if result:
                    key, _, status, headers = result
                    if status == 200:
                        results.append((key, status, headers))
        except KeyboardInterrupt:
            for f in futures:
                f.cancel()
    return results

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()
    acquired = False
    try:
        pool.acquire(timeout=args.timeout)
        acquired = True
    except TimeoutError:
        with progress["lock"]:
            progress["fail"] += 1
        dbg(f"{host_url} pool exhausted")
        return

    try:
        entry = {
            "target": host_url,
            "product": None,
            "label": None,
            "version": None,
            "vulnerable": None,
            "fixed_version": None,
            "headers": [],
            "waf": False,
            "waf_detail": [],
            "error": None,
        }

        if args.product:
            if args.product not in products:
                entry["error"] = f"unknown product {args.product}"
                with progress["lock"]:
                    progress["fail"] += 1
                results.append(entry)
                return
            info = products[args.product]
            marker = info.get("marker")
            probe_path = info.get("probe_path", "/")
            try:
                status, headers, body = fetch_with_retry(host_url, probe_path, args.timeout, args.retries, args.proxy)
                entry["headers"] = check_headers(headers)
                if status in waf_status_codes:
                    entry["waf"] = True
                    entry["waf_detail"] = detect_waf(headers)
                    dbg(f"{host_url} forced product probe -> WAF block ({status})")
                elif body:
                    text = body.decode("utf-8", "replace") if isinstance(body, bytes) else body
                    if marker and marker in text:
                        entry["product"] = args.product
                        entry["label"] = info.get("label", args.product)
                        try:
                            data = json.loads(body)
                            entry["version"] = data.get(info.get("version_field", "version"))
                        except (json.JSONDecodeError, ValueError):
                            pass
            except Exception as exc:
                dbg(f"{host_url} forced product probe failed: {exc}")
        else:
            serverinfo_results = probe_serverinfo(host_url, args.timeout, args.retries, args.proxy)
            for key, version, data, status, headers in serverinfo_results:
                info = products.get(key, {})
                entry["product"] = key
                entry["label"] = info.get("label", key)
                entry["version"] = version
                entry["headers"] = check_headers(headers)
                if status in waf_status_codes:
                    entry["waf"] = True
                    entry["waf_detail"] = detect_waf(headers)
                break

            if not entry["product"]:
                marker_results = detect_product_marker(host_url, args.timeout, args.retries, args.proxy)
                for key, status, headers in marker_results:
                    info = products.get(key, {})
                    entry["product"] = key
                    entry["label"] = info.get("label", key)
                    entry["headers"] = check_headers(headers)
                    if status in waf_status_codes:
                        entry["waf"] = True
                        entry["waf_detail"] = detect_waf(headers)
                    break

            if not entry["headers"]:
                try:
                    status, headers, body = fetch_with_retry(host_url, "/", args.timeout, args.retries, args.proxy)
                    entry["headers"] = check_headers(headers)
                    if status in waf_status_codes:
                        entry["waf"] = True
                        entry["waf_detail"] = detect_waf(headers)
                except Exception as exc:
                    dbg(f"{host_url} header probe failed: {exc}")

        if entry["product"]:
            info = products.get(entry["product"], {})
            fixed_versions = info.get("fixed_versions", [])
            version_tuple = semver(entry["version"])
            if version_tuple:
                vuln = is_vuln(version_tuple, fixed_versions)
                entry["vulnerable"] = vuln
                if vuln:
                    entry["fixed_version"] = fix_for(version_tuple, fixed_versions)
                    alert(f"{host_url} {entry['label']} v{entry['version']} - VULNERABLE (fix: {entry['fixed_version']})")
                    with progress["lock"]:
                        progress["vuln"] += 1
                else:
                    entry["fixed_version"] = None
                    info(f"{host_url} {entry['label']} v{entry['version']} - patched")
                    with progress["lock"]:
                        progress["safe"] += 1
            else:
                warn(f"{host_url} {entry['label']} detected - version unknown, manual verification required")
                with progress["lock"]:
                    progress["unknown"] += 1
        else:
            if args.product:
                entry["error"] = f"forced product '{args.product}' did not validate"
            else:
                entry["error"] = "no Atlassian product detected"
            with progress["lock"]:
                progress["skip"] += 1
            dbg(f"{host_url} no product detected")

        results.append(entry)
    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 acquired:
            pool.release()

def save_json(results, path, meta):
    payload = {
        "tool": "safechecker",
        "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", "label", "version", "vulnerable", "fixed_version", "waf", "headers", "error"]
    try:
        with open(path, "w", newline="", encoding="utf-8") as fh:
            w = csv.DictWriter(fh, fieldnames=fields)
            w.writeheader()
            for r in results:
                w.writerow({
                    "target": r.get("target", ""),
                    "label": r.get("label", "") or "",
                    "version": r.get("version", "") or "",
                    "vulnerable": r.get("vulnerable", ""),
                    "fixed_version": r.get("fixed_version", "") or "",
                    "waf": r.get("waf", False),
                    "headers": "; ".join(r.get("headers", [])) or "",
                    "error": r.get("error", "") or "",
                })
        ok(f"CSV report: {path}")
    except IOError as exc:
        bad(f"cannot write CSV: {exc}")

def save_jsonl(results, path):
    try:
        with open(path, "w", encoding="utf-8") as fh:
            for r in results:
                fh.write(json.dumps(r, default=str) + "\n")
        ok(f"JSONL report: {path}")
    except IOError as exc:
        bad(f"cannot write JSONL: {exc}")

def summary(results, elapsed, show_safe=False):
    total = len(results)
    vuln = sum(1 for r in results if r.get("vulnerable") is True)
    safe = sum(1 for r in results if r.get("vulnerable") is False)
    unknown = sum(1 for r in results if r.get("vulnerable") is None and r.get("product"))
    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"  {green}safe        : {safe}{rst}")
    print(f"  {yellow}unknown     : {unknown}{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"):
                fix = r.get("fixed_version") or "upgrade"
                wtag = f" {blue}[waf]{rst}" if r.get("waf") else ""
                print(f"    {white}{r['target']}{rst} [{r.get('label', '?')}] v{r.get('version', '?')} → fix: {fix}{wtag}")
    if show_safe:
        safe_list = [r for r in results if r.get("vulnerable") is False]
        if safe_list:
            print()
            print(f"  {green}patched targets{rst}")
            for r in safe_list:
                print(f"    {white}{r['target']}{rst} [{r.get('label', '?')}] v{r.get('version', '?')}")
    print(f"{cyan}{'=' * 72}{rst}")

def recommendations():
    print()
    print(f"{cyan}{'=' * 72}{rst}")
    print(f"  {bold}recommendations{rst}")
    print(f"{cyan}{'=' * 72}{rst}")
    print(f"  {yellow}[IMMEDIATE]{rst} Upgrade to fixed versions:")
    print(f"                 Jira DC: 9.12.40 / 10.3.26 / 11.3.12")
    print(f"                 Jira SM DC: 5.12.40 / 10.3.26 / 11.3.12")
    print(f"                 Confluence DC: 9.2.26 / 10.2.19")
    print(f"                 Bitbucket DC: 9.4.26 / 10.2.8 / 10.5.1")
    print(f"                 Bamboo DC: 10.2.24 / 12.1.12")
    print(f"                 Crowd DC: 6.3.7 / 7.0.3 / 7.1.7 / 7.2.4")
    print(f"                 Crucible / Fisheye: 4.9.15")
    print(f"  {yellow}[IMMEDIATE]{rst} Restrict external access to unpatched instances")
    print(f"  {yellow}[HIGH]{rst}      Deploy WAF rule blocking ../ or encoded variants")
    print(f"  {yellow}[HIGH]{rst}      Review access logs for %3a%3a under /download/")
    print(f"  {yellow}[MEDIUM]{rst}    Tomcat RewriteValve rule (Jira, Confluence, Bamboo, Crowd)")
    print(f"  {yellow}[MEDIUM]{rst}    urlrewrite.xml rule (Bitbucket)")
    print(f"  {yellow}[LOW]{rst}       Verify version information against Atlassian advisory")
    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, pool, throttle

    if len(sys.argv) == 1:
        print(banner)
        print(f"{cyan}usage:{rst}")
        print(f"  python3 safechecker.py --target https://jira.example.com")
        print(f"  python3 safechecker.py --target https://jira.example.com --output report.json")
        print(f"  python3 safechecker.py --file targets.txt --threads 32 --output audit.csv")
        print(f"  python3 safechecker.py --target 10.0.0.0/24 --threads 20 --output audit.jsonl")
        print()
        print(f"{cyan}options:{rst}")
        print(f"  --target URL           target URL (single)")
        print(f"  --file FILE            file with targets")
        print(f"  --product KEY          jira|jira_sm|confluence|bitbucket|bamboo|crowd|crucible|fisheye")
        print(f"  --threads N            workers (default 20)")
        print(f"  --timeout SEC          per-request timeout (default 10)")
        print(f"  --retries N            retry count (default 3)")
        print(f"  --rate-limit RPS       max requests per second (default 5.0)")
        print(f"  --pool-size N          connection pool size (default 64)")
        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"  --show-safe            show patched targets in summary")
        print(f"  --quiet                suppress banner and verbose output")
        print(f"  --no-banner            suppress banner only")
        print(f"  --output FILE          report path (.json / .csv / .jsonl)")
        print(f"  -v, --verbose          verbose output")
        print()
        print(f"  {dim}Detection only. No path traversal. No file read. No exploitation.{rst}")
        print()
        return 0

    parser = argparse.ArgumentParser(prog="safechecker", add_help=False)
    parser.add_argument("--target")
    parser.add_argument("--file")
    parser.add_argument("--product")
    parser.add_argument("--threads", type=int, default=20)
    parser.add_argument("--timeout", type=float, default=10.0)
    parser.add_argument("--retries", type=int, default=3)
    parser.add_argument("--rate-limit", type=float, default=5.0)
    parser.add_argument("--pool-size", type=int, default=64)
    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("--show-safe", action="store_true")
    parser.add_argument("--quiet", action="store_true")
    parser.add_argument("--no-banner", 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.quiet:
        log.setLevel(logging.WARNING)

    if not args.no_banner and not args.quiet:
        print(banner)

    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.pool_size < 1:
        bad(f"invalid pool size {args.pool_size}")
        return 1

    if args.rate_limit <= 0:
        warn("rate-limit is 0 (unlimited) - IDS/WAF may trigger on large scans")
    elif args.rate_limit > 100:
        warn(f"rate-limit is very high ({args.rate_limit}) - consider lowering it")

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

    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)
    pool = Pool(args.pool_size)
    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

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

    results = []
    started = time.time()
    progress = {
        "vuln": 0, "safe": 0, "unknown": 0,
        "fail": 0, "skip": 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 KeyboardInterrupt:
        warn("interrupted, saving partial results")
    finally:
        try:
            pool.shutdown()
        except Exception:
            pass

    elapsed = time.time() - started
    summary(results, elapsed, show_safe=args.show_safe)
    recommendations()

    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") is True),
            "safe": sum(1 for r in results if r.get("vulnerable") is False),
            "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)
        elif lower.endswith(".jsonl"):
            save_jsonl(results, args.output)
        else:
            save_json(results, args.output, meta)

    return 0 if not any(r.get("vulnerable") is True 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)