Exploit database

GH-78733ab8d2daff63fc9d1e8e11c46723

hann1bl3l3ct3r/cve-2026-11349

GitHubNot listedPoC
Download repository ZIP

Sources for CVE-2026-11349

1 source

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

Repository files3
hann1bl3l3ct3r/cve-2026-11349Revision 8c1e49363ac5

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

mec-vuln-scanner.py

Python · 18,376 bytes
#!/usr/bin/env python3
"""
Modern Events Calendar (Lite) — Unauthenticated SQL Injection Detection Scanner
===============================================================================

Coordinated-disclosure DETECTION tool (CVE-TBD). Determines, across a list of
domains/IPs, whether a site runs Modern Events Calendar and whether that version is
affected by the unauthenticated `mec_list_load_more` SQL injection.

This is a SCANNER, not an exploit. By design it:
  * sends NO SQL metacharacters and NO injection payload,
  * exfiltrates NO data,
  * is read-only and safe to run against production.

Detection is version-fingerprint based (passive):
  1. homepage HTML  — MEC asset URLs / `?ver=` / markers,
  2. `readme.txt`   — the `Stable tag:` line (authoritative version),
  3. plugin assets  — `assets/css/frontend.min.css` presence (version-unknown fallback).

Optional `--active-check` adds a BENIGN liveness probe of the AJAX endpoint
(`?action=mec_list_load_more&atts[include][]=1` — a plain integer, a normal "load more"
request) to distinguish an ACTIVE/exploitable install from a merely-present one. It still
sends no injection.

Affected range: all releases up to and including 7.33.0 (the current vendor build). The
wordpress.org listing is frozen at 6.5.6 but Webnus distributes newer builds (7.x) off-platform.
Set `FIXED_VERSION` once a patched release ships.

Usage
-----
  python3 mec-vuln-scanner.py example.com
  python3 mec-vuln-scanner.py --targets-file sites.txt --csv results.csv --concurrency 50
  python3 mec-vuln-scanner.py https://a.example https://b.example --active-check --insecure
  python3 mec-vuln-scanner.py --targets-file hosts.txt --json out.json -q

`--targets-file` is one target per line (blank lines and `#` comments ignored). Targets may be
a bare host (`example.com`), `host:port`, or a full URL (`https://example.com/`).

Author: Offensive Security research (coordinated disclosure). Intended for asset owners to
inventory their own estate.
"""

from __future__ import annotations

import argparse
import concurrent.futures
import csv
import json
import logging
import re
import ssl
import sys
import urllib.error
import urllib.parse
import urllib.request
from dataclasses import dataclass, asdict, field
from typing import Optional

LOG = logging.getLogger("mec-scanner")

# --- vulnerability metadata -------------------------------------------------
PLUGIN_SLUGS = ("modern-events-calendar-lite", "modern-events-calendar")
AFFECTED_MAX = "7.33.0"          # last release confirmed vulnerable
FIXED_VERSION: Optional[str] = None  # set to the patched version once Webnus ships a fix
CONTENT_PATH = "/wp-content"     # default; overridden by what the homepage actually references

ASSET_PROBES = (
    "assets/css/frontend.min.css",
    "assets/css/frontend.css",
    "assets/js/frontend.js",
)
STABLE_TAG_RE = re.compile(r"stable\s+tag:\s*([0-9][\w.\-]*)", re.IGNORECASE)
# MEC asset URL carrying a ?ver= in rendered HTML
HTML_VER_RE = re.compile(
    r"plugins/(?:modern-events-calendar-lite|modern-events-calendar)/[^\"'?\s]+"
    r"\?(?:[^\"']*&(?:amp;)?)?ver=([0-9][\w.\-]*)",
    re.IGNORECASE,
)
# Any reference to the MEC plugin directory (presence marker, path-agnostic)
HTML_PATH_RE = re.compile(
    r"plugins/(modern-events-calendar-lite|modern-events-calendar)/", re.IGNORECASE
)
# MEC frontend DOM markers
HTML_MARKER_RE = re.compile(r"(mec-wrap|mec-event|mec_skin|class=\"mec-|id=\"mec_)", re.IGNORECASE)

STATUS_VULNERABLE = "VULNERABLE"
STATUS_POSSIBLE = "POSSIBLY_VULNERABLE"
STATUS_PATCHED = "PATCHED"
STATUS_NOT_DETECTED = "NOT_DETECTED"
STATUS_ERROR = "ERROR"


@dataclass
class Result:
    target: str
    url: str = ""
    status: str = STATUS_NOT_DETECTED
    version: str = ""
    slug: str = ""
    endpoint: str = ""        # "live" | "inactive" | "" (not checked)
    evidence: str = ""
    detail: str = ""
    extras: dict = field(default_factory=dict)


# --- version comparison (stdlib only) --------------------------------------
def parse_version(v: str) -> tuple:
    """Return a comparable tuple for a dotted version like '7.33.0' (ignores non-numeric tail)."""
    parts = []
    for chunk in re.split(r"[.\-]", v.strip()):
        m = re.match(r"^(\d+)", chunk)
        if not m:
            break
        parts.append(int(m.group(1)))
    return tuple(parts) if parts else (0,)


def is_affected(version: Optional[str]) -> Optional[bool]:
    """True/False if decidable from version; None if version unknown."""
    if not version:
        return None
    if FIXED_VERSION and parse_version(version) >= parse_version(FIXED_VERSION):
        return False
    # No fix published (FIXED_VERSION is None) -> every detected version is affected.
    # If a fix exists, anything below it is affected (covers <= AFFECTED_MAX and the whole line).
    return True


# --- HTTP -------------------------------------------------------------------
class Http:
    def __init__(self, timeout: float, insecure: bool, user_agent: str):
        self.timeout = timeout
        self.ua = user_agent
        self.ctx = ssl.create_default_context()
        if insecure:
            self.ctx.check_hostname = False
            self.ctx.verify_mode = ssl.CERT_NONE

    def get(self, url: str, max_bytes: int = 262144) -> tuple[int, str, str, str]:
        """GET a URL. Returns (status, body, final_url, content_type). Raises on transport error."""
        req = urllib.request.Request(url, method="GET")
        req.add_header("User-Agent", self.ua)
        req.add_header("Accept", "*/*")
        try:
            with urllib.request.urlopen(req, timeout=self.timeout, context=self.ctx) as resp:
                body = resp.read(max_bytes)
                ctype = resp.headers.get("Content-Type", "")
                charset = resp.headers.get_content_charset() or "utf-8"
                return resp.status, body.decode(charset, "replace"), resp.geturl(), ctype
        except urllib.error.HTTPError as e:
            try:
                body = e.read(max_bytes).decode("utf-8", "replace")
            except Exception:
                body = ""
            return e.code, body, url, e.headers.get("Content-Type", "") if e.headers else ""


# --- target normalisation ---------------------------------------------------
def candidate_base_urls(target: str) -> list[str]:
    """Turn a user target into ordered base-URL candidates (https first, then http)."""
    target = target.strip().rstrip("/")
    if "://" in target:
        return [target]
    return [f"https://{target}", f"http://{target}"]


# --- detection steps --------------------------------------------------------
def scan_homepage(http: Http, base: str, res: Result) -> Optional[str]:
    """Fetch homepage; populate markers/version hints. Returns a learned content path or None."""
    status, body, final_url, _ = http.get(base + "/")
    res.url = final_url or base
    if not body:
        return None
    learned_path = None
    m_path = HTML_PATH_RE.search(body)
    if m_path:
        res.slug = res.slug or m_path.group(1)
        # learn the content path (everything before "/plugins/<slug>/")
        idx = body.lower().find("/plugins/" + m_path.group(1).lower())
        if idx != -1:
            prefix = body[:idx]
            pm = re.search(r"(/[^\"'\s]*?)$", prefix.rsplit("=", 1)[-1])
            if pm and "/wp-content" in (pm.group(1) + "/wp-content"):
                learned_path = pm.group(1)
        res.extras["homepage_marker"] = "plugin-path"
    m_ver = HTML_VER_RE.search(body)
    if m_ver:
        res.version = res.version or m_ver.group(1)
        res.evidence = "homepage ?ver"
    elif (m_path or HTML_MARKER_RE.search(body)) and not res.evidence:
        res.evidence = "homepage marker"
    return learned_path


def scan_readme(http: Http, base: str, content_path: str, res: Result) -> bool:
    """Fetch readme.txt for each slug; parse the authoritative Stable tag. Returns True if found."""
    slugs = (res.slug,) + PLUGIN_SLUGS if res.slug else PLUGIN_SLUGS
    seen = set()
    for slug in slugs:
        if not slug or slug in seen:
            continue
        seen.add(slug)
        url = f"{base}{content_path}/plugins/{slug}/readme.txt"
        try:
            status, body, _, _ = http.get(url)
        except Exception as exc:  # transport error on this probe — try next
            LOG.debug("readme probe failed %s: %s", url, exc)
            continue
        if status == 200 and "modern events calendar" in body.lower():
            m = STABLE_TAG_RE.search(body)
            res.slug = slug
            res.evidence = "readme.txt Stable tag"
            if m:
                res.version = m.group(1)
            return True
    return False


def scan_assets(http: Http, base: str, content_path: str, res: Result) -> bool:
    """Probe known asset files for presence (version-unknown fallback). Returns True if present."""
    slugs = (res.slug,) + PLUGIN_SLUGS if res.slug else PLUGIN_SLUGS
    for slug in (s for s in dict.fromkeys(slugs) if s):
        for asset in ASSET_PROBES:
            url = f"{base}{content_path}/plugins/{slug}/{asset}"
            try:
                status, _, _, ctype = http.get(url, max_bytes=2048)
            except Exception:
                continue
            if status == 200 and "html" not in ctype.lower():
                res.slug = slug
                if not res.evidence:
                    res.evidence = f"asset {asset}"
                return True
    return False


def check_endpoint(http: Http, base: str, res: Result) -> None:
    """BENIGN liveness probe of the nopriv AJAX action. No injection — a plain integer id.

    A registered/active handler returns MEC output; an unregistered action (plugin inactive)
    makes admin-ajax return the bare string '0'. This only distinguishes active vs inactive.
    """
    qs = urllib.parse.urlencode({"action": "mec_list_load_more", "atts[include][]": "1"})
    url = f"{base}/wp-admin/admin-ajax.php?{qs}"
    try:
        status, body, _, _ = http.get(url, max_bytes=4096)
    except Exception as exc:
        res.extras["endpoint_error"] = str(exc)
        return
    b = body.strip()
    if status == 200 and b != "0" and b != "-1":
        res.endpoint = "live"
    else:
        res.endpoint = "inactive"


# --- per-target orchestration ----------------------------------------------
def scan_target(target: str, http: Http, active_check: bool) -> Result:
    res = Result(target=target)
    last_exc: Optional[Exception] = None
    for base in candidate_base_urls(target):
        try:
            learned = scan_homepage(http, base, res)
            content_path = learned or CONTENT_PATH
            found = scan_readme(http, base, content_path, res)
            if not found and content_path != CONTENT_PATH:
                found = scan_readme(http, base, CONTENT_PATH, res)  # fallback to default path
            if not found and not res.version:
                # assets confirm presence even when readme is blocked / version not yet known
                present = scan_assets(http, base, content_path, res) or scan_assets(
                    http, base, CONTENT_PATH, res
                )
                if not present and not res.evidence:
                    res.status = STATUS_NOT_DETECTED
                    res.detail = "no MEC fingerprint found"
                    return res
            if active_check and (res.version or res.evidence):
                check_endpoint(http, base, res)
            _finalise(res)
            return res
        except (urllib.error.URLError, TimeoutError, ConnectionError, ssl.SSLError) as exc:
            last_exc = exc
            continue  # try next scheme (https -> http)
    res.status = STATUS_ERROR
    res.detail = f"unreachable: {last_exc}"
    return res


def _finalise(res: Result) -> None:
    detected = bool(res.version or res.evidence or res.slug)
    if not detected:
        res.status = STATUS_NOT_DETECTED
        return
    affected = is_affected(res.version)
    if affected is False:
        res.status = STATUS_PATCHED
        res.detail = f"version {res.version} >= fixed {FIXED_VERSION}"
    elif affected is True:
        res.status = STATUS_VULNERABLE
        res.detail = f"MEC {res.version or '?'} (affected)"
    else:
        res.status = STATUS_POSSIBLE
        res.detail = "MEC present, version undetermined (treat as affected until confirmed)"
    if res.endpoint == "inactive" and res.status in (STATUS_VULNERABLE, STATUS_POSSIBLE):
        res.detail += "; AJAX endpoint inactive (installed but maybe deactivated)"
    elif res.endpoint == "live":
        res.detail += "; AJAX endpoint live"


# --- output -----------------------------------------------------------------
_COLORS = {
    STATUS_VULNERABLE: "\033[31m", STATUS_POSSIBLE: "\033[33m",
    STATUS_PATCHED: "\033[32m", STATUS_NOT_DETECTED: "\033[90m", STATUS_ERROR: "\033[35m",
}


def print_table(results: list[Result], color: bool) -> None:
    w = max((len(r.target) for r in results), default=6)
    w = min(max(w, 6), 50)
    for r in results:
        tag = r.status
        if color and sys.stdout.isatty():
            tag = f"{_COLORS.get(r.status, '')}{r.status}\033[0m"
            pad = " " * max(0, 19 - len(r.status))
        else:
            pad = " " * max(0, 19 - len(r.status))
        ver = r.version or "-"
        print(f"  {r.target[:w].ljust(w)}  {tag}{pad} {ver.ljust(10)} {r.detail}")


def write_csv(results: list[Result], path: str) -> None:
    with open(path, "w", newline="", encoding="utf-8") as fh:
        wr = csv.writer(fh)
        wr.writerow(["target", "url", "status", "version", "slug", "endpoint", "evidence", "detail"])
        for r in results:
            wr.writerow([r.target, r.url, r.status, r.version, r.slug, r.endpoint, r.evidence, r.detail])


def write_json(results: list[Result], path: str) -> None:
    with open(path, "w", encoding="utf-8") as fh:
        json.dump([asdict(r) for r in results], fh, indent=2)


# --- main -------------------------------------------------------------------
def load_targets(args: argparse.Namespace) -> list[str]:
    targets: list[str] = list(args.targets)
    if args.targets_file:
        with open(args.targets_file, encoding="utf-8") as fh:
            for line in fh:
                line = line.strip()
                if line and not line.startswith("#"):
                    targets.append(line)
    # de-dup, preserve order
    return list(dict.fromkeys(targets))


def main() -> int:
    ap = argparse.ArgumentParser(
        description="Detect Modern Events Calendar unauthenticated SQLi exposure across many sites.",
        epilog="Detection only — sends no injection payload and exfiltrates no data.",
    )
    ap.add_argument("targets", nargs="*", help="Hosts/URLs to scan (e.g. example.com).")
    ap.add_argument("--targets-file", help="File with one target per line (# comments allowed).")
    ap.add_argument("--concurrency", type=int, default=20, help="Parallel workers (default 20).")
    ap.add_argument("--timeout", type=float, default=10.0, help="Per-request timeout s (default 10).")
    ap.add_argument("--active-check", action="store_true",
                    help="Add a BENIGN AJAX liveness probe (integer id; no injection).")
    ap.add_argument("--insecure", action="store_true", help="Skip TLS certificate verification.")
    ap.add_argument("--user-agent", default="MEC-VulnScanner/1.0 (+coordinated-disclosure)",
                    help="HTTP User-Agent.")
    ap.add_argument("--csv", help="Write results to this CSV file.")
    ap.add_argument("--json", dest="json_out", help="Write results to this JSON file.")
    ap.add_argument("--no-color", action="store_true", help="Disable coloured output.")
    ap.add_argument("-q", "--quiet", action="store_true", help="Only print VULNERABLE/POSSIBLE rows.")
    ap.add_argument("-v", "--verbose", action="store_true", help="Debug logging.")
    args = ap.parse_args()

    logging.basicConfig(
        level=logging.DEBUG if args.verbose else logging.WARNING,
        format="%(levelname)s %(message)s",
    )

    targets = load_targets(args)
    if not targets:
        ap.error("no targets given (positional args or --targets-file)")

    http = Http(timeout=args.timeout, insecure=args.insecure, user_agent=args.user_agent)
    results: list[Result] = []
    LOG.info("scanning %d target(s) with %d workers", len(targets), args.concurrency)
    with concurrent.futures.ThreadPoolExecutor(max_workers=args.concurrency) as ex:
        futures = {ex.submit(scan_target, t, http, args.active_check): t for t in targets}
        for fut in concurrent.futures.as_completed(futures):
            try:
                results.append(fut.result())
            except Exception as exc:  # never let one target kill the run
                results.append(Result(target=futures[fut], status=STATUS_ERROR, detail=str(exc)))

    order = {STATUS_VULNERABLE: 0, STATUS_POSSIBLE: 1, STATUS_PATCHED: 2,
             STATUS_NOT_DETECTED: 3, STATUS_ERROR: 4}
    results.sort(key=lambda r: (order.get(r.status, 9), r.target))

    shown = [r for r in results if not args.quiet or r.status in (STATUS_VULNERABLE, STATUS_POSSIBLE)]
    fixed = FIXED_VERSION or "no patch published"
    print(f"\nModern Events Calendar - unauthenticated SQLi exposure scan "
          f"(affected: all <= {AFFECTED_MAX}; fixed: {fixed})\n")
    print_table(shown, color=not args.no_color)

    counts = {s: sum(1 for r in results if r.status == s) for s in order}
    print(
        "\nSummary: "
        f"{counts[STATUS_VULNERABLE]} vulnerable, "
        f"{counts[STATUS_POSSIBLE]} possibly, "
        f"{counts[STATUS_PATCHED]} patched, "
        f"{counts[STATUS_NOT_DETECTED]} not detected, "
        f"{counts[STATUS_ERROR]} errors  (of {len(results)})"
    )

    if args.csv:
        write_csv(results, args.csv)
        print(f"[+] CSV  written: {args.csv}")
    if args.json_out:
        write_json(results, args.json_out)
        print(f"[+] JSON written: {args.json_out}")

    # exit 2 if anything is vulnerable/possible (useful for CI/cron), else 0
    return 2 if (counts[STATUS_VULNERABLE] or counts[STATUS_POSSIBLE]) else 0


if __name__ == "__main__":
    try:
        sys.exit(main())
    except KeyboardInterrupt:
        sys.exit(130)