Exploit databaseDownload repository ZIP
GH-be1f712684e063df26f8a3eadc3e28b0
catermaozi/cve-2026-111497-poc
Sources for CVE-2026-111497
61 sourcesPreferred order: Exploit-DB, Metasploit, then GitHub repositories by stars. Open preferred source
Repository files2
catermaozi/cve-2026-111497-pocRevision ac6c4e343127
Files from this repository share one source choice. Supporting files may cover other vulnerabilities.
tools/verify_brotli.py
Python · 24,108 bytes#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Cross-release verification harness for CVE-2026-111497.
Answers two questions the main tool cannot answer on its own:
1. Which Node.js release lines actually carry the vulnerable code?
-> `source`: pulls deps/brotli from nodejs/node at each tag and looks for
the three markers that define the bug.
2. Do those lines behave the same as a known-vulnerable runtime?
-> `runtime`: runs one identical set of boundary streams through the real
decoder of each downloaded build and diffs the error codes.
Both questions are answered without running any exploit payload: `source`
reads text from GitHub, `runtime` decodes bytes locally.
Usage
python3 tools/verify_brotli.py source
python3 tools/verify_brotli.py fetch --node-dir tools/node
python3 tools/verify_brotli.py runtime --node-dir tools/node
python3 tools/verify_brotli.py all
Requires: python 3.8+, `brotli` for seed generation.
`source` needs network access to raw.githubusercontent.com.
`fetch` needs network access to nodejs.org and about 40 MB per build.
`runtime` needs the builds on disk and nothing else.
"""
from __future__ import print_function
import argparse
import base64
import json
import os
import platform
import re
import ssl
import struct
import subprocess
import sys
import tempfile
import zipfile
try:
import urllib.request as urlreq
except ImportError: # pragma: no cover
import urllib2 as urlreq # type: ignore
HERE = os.path.dirname(os.path.abspath(__file__))
REPO = os.path.dirname(HERE)
TOOL_PATH = os.path.join(REPO, 'cve_2026_111497.py')
# Release lines that matter for this verification. The first three are EOL and
# will never receive a fix; the last three bracket the patch boundary.
DEFAULT_TAGS = [
'v16.20.2', # 16.x, EOL 2023-09
'v18.20.4', # 18.x, EOL 2025-04
'v19.9.0', # 19.x, EOL 2023-06 (odd-numbered, never LTS)
'v22.16.0', # unpatched reference
'v22.23.4', # first patched 22.x
'v24.22.1', # first patched 24.x
]
SOURCE_BASE = 'https://raw.githubusercontent.com/nodejs/node/{tag}/deps/brotli/c/'
DIST_BASE = 'https://nodejs.org/dist/{tag}/node-{tag}-{plat}.zip'
# ---------------------------------------------------------------- output helpers
_TTY = sys.stdout.isatty()
def _c(code, s):
return '\033[%sm%s\033[0m' % (code, s) if _TTY else s
def head(s):
print('\n%s\n%s' % (_c('1;33', s), '-' * 72))
def ok(s):
print('%s %s' % (_c('32', '[ok]'), s))
def warn(s):
print('%s %s' % (_c('33', '[warn]'), s))
def bad(s):
print('%s %s' % (_c('31', '[fail]'), s))
def log(s):
print(' %s' % s)
# ---------------------------------------------------------------- tool import
def load_tool():
"""Import the main tool so the verification uses exactly the same stream
builders as `probe` -- otherwise the two would drift apart."""
import importlib.util
spec = importlib.util.spec_from_file_location('brotli_tool', TOOL_PATH)
mod = importlib.util.module_from_spec(spec)
spec.loader.exec_module(mod)
return mod
# ---------------------------------------------------------------- HTTP
def _ctx():
# nodejs.org and raw.githubusercontent.com both have valid certs; the
# relaxed context is only a convenience for networks with a TLS interceptor.
if os.environ.get('VERIFY_INSECURE_TLS'):
c = ssl.create_default_context()
c.check_hostname = False
c.verify_mode = ssl.CERT_NONE
return c
return ssl.create_default_context()
def http_get(url, timeout=60, attempts=4):
last = None
for i in range(attempts):
try:
req = urlreq.Request(url, headers={'User-Agent': 'cve-2026-111497-verify'})
return urlreq.urlopen(req, timeout=timeout, context=_ctx()).read()
except Exception as e: # noqa: BLE001
last = e
if i < attempts - 1:
import time
time.sleep(1.5 * (i + 1))
raise last # type: ignore[misc]
def http_text(url, **kw):
return http_get(url, **kw).decode('utf-8', 'replace')
def write_json(path, obj):
d = os.path.dirname(os.path.abspath(path))
if d:
os.makedirs(d, exist_ok=True)
with open(path, 'w', encoding='utf-8') as f:
json.dump(obj, f, indent=2, ensure_ascii=False)
ok('wrote %s' % path)
# ===========================================================================
# source
# ===========================================================================
SAFE_MACRO_RE = re.compile(r'#define BROTLI_SAFE\(METHOD\)(.*?)\n\n', re.S)
DROPS_RESULT_RE = re.compile(r'\}\s*else\s*\{\s*\\?\s*\n?\s*METHOD\s*;')
BLOCK_LEN_INIT_RE = re.compile(r'block_length\[[^\]]*\]\s*=\s*([^;]+);')
# The decisive marker. There are exactly three block-switch call sites:
# unpatched -> BROTLI_SAFE(DecodeCommandBlockSwitch(s)); (result dropped)
# patched -> BROTLI_SAFE_WITH_STATUS(DecodeCommandBlockSwitch(s));
BLOCK_SWITCH_UNSAFE_RE = re.compile(
r'(?<!WITH_STATUS\()BROTLI_SAFE\(\s*Decode\w*BlockSwitch')
BLOCK_SWITCH_STATUS_RE = re.compile(
r'BROTLI_SAFE_WITH_STATUS\(\s*Decode\w*BlockSwitch')
def brotli_version(text):
"""Read the version out of common/version.h.
Two historical shapes exist:
1.0.9 -> #define BROTLI_VERSION 0x00010009
1.1.0 and up -> BROTLI_VERSION_MAJOR / _MINOR / _PATCH defines
"""
major = re.search(r'#define\s+BROTLI_VERSION_MAJOR\s+(\d+)', text)
minor = re.search(r'#define\s+BROTLI_VERSION_MINOR\s+(\d+)', text)
patch = re.search(r'#define\s+BROTLI_VERSION_PATCH\s+(\d+)', text)
if major and minor and patch:
return '%s.%s.%s' % (major.group(1), minor.group(1), patch.group(1))
m = re.search(r'#define\s+BROTLI_VERSION\s+(0x[0-9A-Fa-f]+)', text)
if m:
v = int(m.group(1), 16)
return '%d.%d.%d' % ((v >> 24) & 0xFF, (v >> 12) & 0xFFF, v & 0xFFF)
return '?'
def inspect_tag(tag):
"""Return a dict describing the three vulnerability markers for one tag."""
row = {'tag': tag, 'error': None}
try:
dec = http_text(SOURCE_BASE.format(tag=tag) + 'dec/decode.c')
st = http_text(SOURCE_BASE.format(tag=tag) + 'dec/state.c')
ver = http_text(SOURCE_BASE.format(tag=tag) + 'common/version.h')
except Exception as e: # noqa: BLE001
row['error'] = str(e)[:120]
return row
row['brotli'] = brotli_version(ver)
# marker 1+2: the macro exists and its unsafe branch drops the result
m = SAFE_MACRO_RE.search(dec)
row['macro'] = bool(m)
row['drops_result'] = bool(m and DROPS_RESULT_RE.search(m.group(1)))
# marker 3: how the three block-switch call sites propagate failure.
# This is the decisive signal -- the macro itself survives the patch,
# because other call sites still use it.
row['bs_unsafe'] = len(BLOCK_SWITCH_UNSAFE_RE.findall(dec))
row['bs_status'] = len(BLOCK_SWITCH_STATUS_RE.findall(dec))
row['safe_calls'] = len(re.findall(r'BROTLI_SAFE\s*\(', dec))
row['safe_with_status'] = len(re.findall(r'#define BROTLI_SAFE_WITH_STATUS', dec))
if row['bs_status'] or row['safe_with_status']:
row['return_type'] = 'BrotliDecoderErrorCode'
else:
row['return_type'] = 'BROTLI_BOOL'
# marker 4: the counter starts at the metablock cap
m2 = BLOCK_LEN_INIT_RE.search(st)
row['block_len_init'] = re.sub(r'\s+', ' ', m2.group(1).strip()) if m2 else '?'
row['block_len_is_cap'] = 'BLOCK_SIZE_CAP' in row['block_len_init'] or \
'1U << 24' in row['block_len_init'] or '1 << 24' in row['block_len_init']
# block-switch sites differ in count between brotli generations:
# 1.0.9 -> 4 sites (DecodeLiteralBlockSwitch appears twice)
# 1.1.0+ -> 3 sites
# so the test is "any site still on the result-dropping macro", not a count.
row['vulnerable'] = bool(row['macro'] and row['drops_result']
and row['bs_unsafe'] >= 1
and row['bs_status'] == 0
and row['block_len_is_cap'])
return row
def cmd_source(args, tool=None):
head('source-level verification')
log('source: %s' % SOURCE_BASE.format(tag='<tag>'))
log('reading dec/decode.c, dec/state.c, common/version.h per tag')
print('')
rows = []
for tag in args.tags:
sys.stdout.write(' %-10s ' % tag)
sys.stdout.flush()
r = inspect_tag(tag)
rows.append(r)
if r['error']:
print('%s %s' % (_c('31', 'FETCH FAILED'), r['error']))
else:
print('%s brotli %s' % (_c('32', 'ok'), r['brotli']))
good = [r for r in rows if not r['error']]
if not good:
bad('no tag could be fetched')
return 2
print('')
print('| tag | brotli | block-switch call sites | `block_length[]` init | vulnerable |')
print('|---|---|---|---|---|')
for r in rows:
if r['error']:
print('| %s | fetch failed | | | ? |' % r['tag'])
continue
if r['bs_status']:
sites = '`BROTLI_SAFE_WITH_STATUS` x%d' % r['bs_status']
else:
sites = '`BROTLI_SAFE` x%d (result dropped)' % r['bs_unsafe']
print('| %s | %s | %s | `%s` | **%s** |' % (
r['tag'], r['brotli'], sites, r['block_len_init'],
'yes' if r['vulnerable'] else 'no'))
vuln = [r for r in good if r['vulnerable']]
fixed = [r for r in good if not r['vulnerable']]
print('')
if vuln:
ok('carry the vulnerable code: %s' % ', '.join(r['tag'] for r in vuln))
if fixed:
ok('carry the fix: %s' % ', '.join(r['tag'] for r in fixed))
# The patched tags keep BROTLI_SAFE for unrelated call sites; make that
# explicit so a reader does not mistake "macro still present" for "unfixed".
for r in fixed:
if r['safe_with_status']:
log('%s adds BROTLI_SAFE_WITH_STATUS x%d, which propagates '
'FORMAT_BLOCK_SWITCH' % (r['tag'], r['safe_with_status']))
if args.json:
print('')
write_json(args.json, rows)
return 0
# ===========================================================================
# fetch
# ===========================================================================
def host_platform():
sysname = platform.system().lower()
if sysname == 'windows':
return 'win-x64', 'node.exe'
if sysname == 'darwin':
return 'darwin-x64', 'bin/node'
return 'linux-x64', 'bin/node'
def cmd_fetch(args, tool=None):
head('download official builds')
if args.platform:
plat = args.platform
inner = 'node.exe' if plat.startswith('win') else 'bin/node'
else:
plat, inner = host_platform()
outdir = os.path.abspath(args.node_dir)
os.makedirs(outdir, exist_ok=True)
log('platform: %s' % plat)
log('target: %s' % outdir)
print('')
rc = 0
for tag in args.tags:
exe = os.path.join(outdir, '%s-node%s' % (tag, '.exe' if plat.startswith('win') else ''))
if os.path.exists(exe) and os.path.getsize(exe) > 10 * 1024 * 1024:
ok('%-10s cached (%d MB)' % (tag, os.path.getsize(exe) // (1 << 20)))
continue
url = DIST_BASE.format(tag=tag, plat=plat)
sys.stdout.write(' %-10s downloading ' % tag)
sys.stdout.flush()
tmp = os.path.join(outdir, tag + '.zip')
try:
data = http_get(url, timeout=300)
print('%d MB' % (len(data) // (1 << 20)))
with open(tmp, 'wb') as f:
f.write(data)
with zipfile.ZipFile(tmp) as z:
try:
member = next(n for n in z.namelist()
if n.endswith('/' + inner) and n.count('/') == inner.count('/') + 1)
except StopIteration:
bad('archive has no %s' % inner)
rc = 1
continue
with z.open(member) as src, open(exe, 'wb') as dst:
dst.write(src.read())
if not plat.startswith('win'):
os.chmod(exe, 0o755)
ok('%-10s extracted %s (%d MB)' % (tag, member, os.path.getsize(exe) // (1 << 20)))
except Exception as e: # noqa: BLE001
bad('%-10s %s' % (tag, str(e)[:120]))
rc = 1
finally:
if os.path.exists(tmp):
os.remove(tmp)
return rc
# ===========================================================================
# runtime
# ===========================================================================
PROBE_JS = r"""
const fs = require("fs");
const zlib = require("zlib");
const cfg = JSON.parse(fs.readFileSync(process.argv[2], "utf8"));
const results = [];
for (const item of cfg.inputs) {
const buf = Buffer.from(item.b64, "base64");
const row = { name: item.name, outcome: null };
try {
const out = zlib.brotliDecompressSync(buf, { maxOutputLength: 8 * 1024 * 1024 });
row.outcome = "decompressed";
row.bytes = out.length;
} catch (e) {
row.outcome = "error";
row.code = e.code || null;
row.errcode = typeof e.errno === "number" ? e.errno : null;
row.message = String(e.message || "").slice(0, 160);
}
results.push(row);
}
console.log("@@R@@" + JSON.stringify(results));
"""
FINGERPRINT_JS = (
'const z=require("zlib");'
'console.log(JSON.stringify({node:process.versions.node,'
'brotli:process.versions.brotli,zlib:process.versions.zlib,'
'sync:typeof z.brotliDecompressSync,'
'stream:typeof z.createBrotliDecompress,'
'maxOut:(()=>{try{z.brotliDecompressSync(require("zlib").brotliCompressSync(Buffer.alloc(0)),'
'{maxOutputLength:1});return "yes";}catch(e){return "no";}})()}));'
)
def build_streams(tool):
"""The identical input set every build must decode. Same construction as
`probe`, extended with truncations and header bit flips."""
if tool.brotli is None:
raise SystemExit("python 'brotli' package required: pip install brotli")
inputs = [('valid-baseline', tool.brotli.compress(b'hello brotli ' * 100, quality=11))]
info = None
blobby = None
seeds = tool.make_seeds()
big = [c for n, c in seeds if n.startswith('q11')]
if big:
blobby = max(big, key=len)
try:
info = tool.parse_prefix(blobby)
inputs.append(('q11-raw', blobby))
except Exception: # noqa: BLE001
blobby = None
if blobby:
for which in ('L', 'I', 'D'):
try:
inputs.append(('nbl%s->2' % which,
tool.rewrite_nbltypes(blobby, which, 2)))
except Exception: # noqa: BLE001
pass
try:
if info and info.get('NBLTYPES%s' % which, 0) >= 1:
inputs.append(('nbl%s->0' % which,
tool.rewrite_nbltypes(blobby, which, 0)))
except Exception: # noqa: BLE001
pass
for name, data in list(inputs):
inputs.append((name + '-trunc', data[:max(2, len(data) // 2)]))
b = bytearray(data)
if len(b) > 4:
b[2] ^= 0xFF
inputs.append((name + '-flip', bytes(b)))
# de-duplicate by content while keeping the first name
seen = set()
unique = []
for n, d in inputs:
if d in seen:
continue
seen.add(d)
unique.append((n, d))
return unique
def exe_for(node_dir, tag):
for name in ('%s-node.exe' % tag, '%s-node' % tag):
p = os.path.join(node_dir, name)
if os.path.exists(p):
return p
return None
def cmd_runtime(args, tool=None):
tool = tool or load_tool()
head('runtime verification')
node_dir = os.path.abspath(args.node_dir)
streams = build_streams(tool)
log('%d distinct streams, each decoded by every build' % len(streams))
print('')
for n, d in streams:
print(' %-26s %7d bytes' % (n, len(d)))
workdir = tempfile.mkdtemp(prefix='cve111497-verify-')
js = os.path.join(workdir, 'probe.js')
cfg = os.path.join(workdir, 'probe.json')
with open(js, 'w', encoding='utf-8') as f:
f.write(PROBE_JS)
with open(cfg, 'w', encoding='utf-8') as f:
json.dump({'inputs': [{'name': n, 'b64': base64.b64encode(d).decode()}
for n, d in streams]}, f)
results = {}
print('')
for tag in args.tags:
exe = exe_for(node_dir, tag)
if not exe:
warn('%-10s build missing, run `fetch` first' % tag)
continue
try:
fp_out = subprocess.run([exe, '-e', FINGERPRINT_JS],
capture_output=True, text=True, timeout=90)
finger = json.loads(fp_out.stdout.strip() or '{}')
except Exception as e: # noqa: BLE001
finger = {'error': str(e)[:120]}
try:
p = subprocess.run([exe, js, cfg], capture_output=True, text=True,
timeout=args.timeout)
rows = None
for line in p.stdout.splitlines():
if line.startswith('@@R@@'):
rows = json.loads(line[len('@@R@@'):])
if rows is None:
rows = {'error': (p.stderr or p.stdout)[:300]}
except subprocess.TimeoutExpired:
rows = {'error': 'TIMEOUT after %ss' % args.timeout}
results[tag] = {'fingerprint': finger, 'rows': rows}
if isinstance(rows, dict):
warn('%-10s %s' % (tag, rows.get('error')))
else:
ok('%-10s node %s, brotli %s' % (tag, finger.get('node'),
finger.get('brotli')))
if not results:
bad('nothing ran')
return 2
usable = [t for t in args.tags if t in results and not isinstance(results[t]['rows'], dict)]
if not usable:
bad('no build produced a parseable result')
return 2
# ------------------------------------------------------------ compare
# Compare on (outcome, errno) -- NOT on the error code name. brotli 1.1.0
# renamed the format errors (ERR_CL_SPACE -> ERR__ERROR_FORMAT_CL_SPACE)
# while keeping the same numeric value, so names do not indicate a fix.
def code_map(tag):
return {r['name']: {'outcome': r['outcome'],
'code': r.get('code'),
'errcode': r.get('errcode')}
for r in results[tag]['rows']}
maps = {t: code_map(t) for t in usable}
ref = args.reference if args.reference in maps else usable[0]
print('')
head('decoder behaviour per build')
names = [n for n, _ in streams]
widths = max(11, max(len(t) for t in usable))
print('%-26s %s' % ('stream', ' '.join('%-*s' % (widths, t) for t in usable)))
print('-' * (26 + (widths + 1) * len(usable)))
all_same = True
for n in names:
cells = []
for t in usable:
v = maps[t].get(n)
if v is None:
cells.append('-' * widths)
continue
cells.append('%-*s' % (widths, v['outcome'][:widths]))
keys = {(maps[t][n]['outcome'], maps[t][n]['errcode'])
for t in usable if n in maps[t]}
same = len(keys) <= 1
if not same:
all_same = False
print('%-26s %s %s' % (n, ' '.join(cells),
_c('32', 'same') if same else _c('31', 'DIFF')))
print('')
head('error codes')
for t in usable:
buckets = {}
for r in results[t]['rows']:
k = r.get('code') or r['outcome']
buckets[k] = buckets.get(k, 0) + 1
print(' %-10s %s' % (t, ', '.join('%s x%d' % (k, v)
for k, v in sorted(buckets.items()))))
print('')
log('16/18/19 print ERR_CL_SPACE where 22.x prints ERR__ERROR_FORMAT_CL_SPACE:')
log('brotli 1.1.0 renamed those constants. The errno behind them is identical.')
# ------------------------------------------------------------ verdict
print('')
head('verdict')
if len(usable) == 1:
warn('only one build was usable (%s) -- nothing to diff' % usable[0])
log('pass --node-dir with more builds, or run `fetch` without --tags')
elif all_same:
ok('every build produced identical decoder behaviour (same errno)')
log('the EOL lines are indistinguishable from the reference runtime')
else:
warn('behaviour differs between builds, inspect the DIFF rows above')
log('DIFF here means a different errno, not merely a renamed code')
saw_switch = any('BLOCK_SWITCH' in str(v) for m in maps.values() for v in m.values())
if saw_switch:
ok('a build answered FORMAT_BLOCK_SWITCH')
else:
log('no FORMAT_BLOCK_SWITCH anywhere. That is expected and is NOT a')
log('patch indicator: the fix only changes behaviour on the branch that')
log('executes a block switch, which needs block_length[1] driven from')
log('1<<24 to zero -- 16,777,216 commands inside one metablock. No such')
log('stream is public. Use `source` to decide whether a build is patched.')
if args.json:
write_json(args.json, results)
return 0
# ===========================================================================
def cmd_all(args, tool=None):
rc = cmd_source(args, tool)
if rc != 0:
return rc
rc = cmd_fetch(args, tool)
if rc != 0:
warn('some builds missing, runtime matrix will be partial')
rc2 = cmd_runtime(args, tool)
return rc2
def main(argv):
ap = argparse.ArgumentParser(
prog='verify_brotli.py',
description='Cross-release verification for CVE-2026-111497.',
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog=__doc__)
sub = ap.add_subparsers(dest='cmd')
def common(p):
p.add_argument('--tags', nargs='+', default=DEFAULT_TAGS,
help='Node.js tags to inspect (default: the six release lines)')
p.add_argument('--json', metavar='PATH', help='write raw results as JSON')
p_src = sub.add_parser('source', help='inspect deps/brotli at each tag on GitHub')
common(p_src)
p_fetch = sub.add_parser('fetch', help='download official builds')
p_fetch.add_argument('--tags', nargs='+', default=DEFAULT_TAGS)
p_fetch.add_argument('--json', metavar='PATH')
p_fetch.add_argument('--node-dir', default=os.path.join(HERE, 'node'))
p_fetch.add_argument('--platform', default=None,
help='win-x64 | linux-x64 | darwin-x64 (default: host)')
p_run = sub.add_parser('runtime', help='run the stream matrix against local builds')
p_run.add_argument('--tags', nargs='+', default=DEFAULT_TAGS)
p_run.add_argument('--json', metavar='PATH')
p_run.add_argument('--node-dir', default=os.path.join(HERE, 'node'))
p_run.add_argument('--reference', default='v22.16.0',
help='tag treated as the known-vulnerable reference')
p_run.add_argument('--timeout', type=int, default=600)
p_all = sub.add_parser('all', help='source + fetch + runtime')
p_all.add_argument('--tags', nargs='+', default=DEFAULT_TAGS)
p_all.add_argument('--json', metavar='PATH')
p_all.add_argument('--node-dir', default=os.path.join(HERE, 'node'))
p_all.add_argument('--platform', default=None)
p_all.add_argument('--reference', default='v22.16.0')
p_all.add_argument('--timeout', type=int, default=600)
args = ap.parse_args(argv)
if not args.cmd:
ap.print_help()
return 0
tool = None
if args.cmd in ('runtime', 'all'):
tool = load_tool()
return {'source': cmd_source, 'fetch': cmd_fetch,
'runtime': cmd_runtime, 'all': cmd_all}[args.cmd](args, tool)
if __name__ == '__main__':
sys.exit(main(sys.argv[1:]))