Background

sqlparse is a widely used, non-validating SQL parser for Python. It splits scripts into statements, pretty-prints queries and identifies tokens such as keywords and identifiers. It is a dependency of Django, among other projects, and it ships a command-line formatter called sqlformat.

One of its options is a code-generating output mode. Passing output_format='php' (or python) does not just format the SQL. It wraps the query in source code that assigns it to a variable, so the result can be pasted into a program. The PHP form looks roughly like $sql = "SELECT ...";.

Terms used below:

  • Code generation is a program writing source code for another program to run later.
  • Escaping means rewriting characters that have a special meaning in the target language so they are treated as plain text.
  • String interpolation is a language feature where variable names or expressions inside a string are replaced by their values when the string is evaluated.

Summary

SQL text can become executable PHP expressions when converted through the PHP output formatter and then run as generated source. The formatter escapes quotes and backslashes but leaves dollar signs unchanged inside a double-quoted PHP string, where they trigger interpolation.

The payload stays inside the generated string literal while PHP evaluates an embedded expression. It bypasses the earlier quote-and-backslash fix without undoing that fix’s protection against string breakout. Formatting alone does not execute PHP, so the consumer’s decision to run the generated artifact is part of the attack chain.

How the Vulnerability Works

Whenever a program writes code that contains untrusted data, it must escape that data for the language it is writing. Each language has its own special characters. The bug here is a formatter that knew the rules for one hazard in PHP strings and missed another.

PHP has two common kinds of quoted string. In a single-quoted string, nearly everything is literal. In a double-quoted string, PHP looks for $variable and {$expression} and evaluates them. sqlparse’s PHP mode uses double quotes. It escapes the double quote and, since an earlier fix (GHSA-3496-9g83-7v6x), the backslash. Together these stop an attacker from closing the string and appending their own statements. It does not escape the dollar sign.

So SQL text such as this:

SQL
SELECT '{$e->msg()}' AS note

is turned into this generated PHP:

PHP
$sql = "SELECT '{$e->msg()}' AS note";

The attacker never leaves the string, so the earlier protection is not triggered. When PHP runs the generated file, it sees {$e->msg()} inside a double-quoted string, evaluates it, and calls the method. In the proof, the consumer had an object in scope with a method that recorded the call. Any expression that PHP is willing to interpolate can be written into the string.

The PHP interpolation syntax is richer than this one example. The published advisory also demonstrates reading a variable from the surrounding scope ('$DB_PASSWORD') and, through PHP’s curly syntax, running a shell command with system().

The Python output mode uses a single-quoted literal, and the same input stayed inert there. The attack also has a precondition that matters: nothing happens until a developer or application actually executes or imports the generated snippet. This is code injection (CWE-94), and the lesson is that escaping has to be written once per target language and tested with that language’s own special characters.

Prerequisites

The attacker controls SQL processed through output_format='php' or the equivalent CLI mode (sqlformat -l php). A developer or application must subsequently execute or import the generated snippet.

Ordinary SQL parsing, splitting and formatting without this mode do not reach the code-generation boundary. The proof of concept used a PHP consumer with a method available in scope. PHP evaluated the generated source. No SQL-side database vulnerability was required.

Attack Path

Attack route
Attacker routeMitigationCtrl + scroll to zoom
  1. START
    Attacker influences SQL text
  2. STEP 01
    Consumer requests PHP source output
  3. STEP 02
    Formatter leaves interpolation syntax active

    Quote escaping does not prevent expressions inside a double-quoted string.

    MITIGATION Escape dollar signs in generated PHP strings

  4. STEP 03
    Generated snippet is executed or imported

    MITIGATION Keep untrusted queries out of executable source artifacts

  5. STEP 04
    PHP evaluates attacker-controlled expressions

Root Cause

OutputPHPFilter surrounds the SQL with a double-quoted PHP string. Its escaping sequence handles backslashes and double quotes, but not dollar signs. A SQL literal containing {$e->msg()} therefore becomes an interpolation expression when the generated source runs.

The earlier fix addressed a backslash neutralizing a quote escape. That correction remains effective for its original payload. Interpolation follows a different language rule and needs neither a quote nor a newline to escape the surrounding string.

The Python output mode uses a single-quoted literal with the escapes needed by that language. The same input remained data in the control test. Output generators need language-specific escaping even when they share the input and general formatting logic.

Validation

The proof of concept tested sqlparse revision 60cdc64 with the PHP 8 command-line interpreter. It generated snippets from benign SQL, the earlier advisory’s backslash payload and SQL containing a method-call expression. The consumer supplied the method and observed its invocation.

Input and output modeExpected boundaryRecorded result
Benign SQL to PHPReproduce the query as dataFaithful round trip
Earlier backslash-breakout casePreserve the published fixNo execution
Interpolation expression to PHPKeep SQL content inertConsumer method invoked
Same expression to PythonKeep SQL content inertNo execution

These controls distinguished interpolation from a regression of the old fix. The published advisory also documents command execution with system() and variable substitution on 0.6.0, observed on PHP 8.1 and 8.4. The table above covers the method-call test.

Impact

Executing the snippet can run expressions with the PHP process’s permissions and expose variables in the surrounding scope. Plain variable interpolation can also replace query contents with a consumer variable, changing generated data even without an explicit function call.

Execution or import is required. Output that is only displayed or stored as text is not affected. Overview uses GitHub’s published 6.2 assessment under CVSS v4.0.

Remediation

Upgrade to 0.6.1 or later, the patched version identified by the advisory. The PHP output path must escape dollar signs along with backslashes and quotes, or use a representation that does not interpolate query contents.

Before upgrading, avoid executing generated PHP containing attacker-influenced SQL. Keep query text as data instead of building executable source around it. Tests should cover literal dollar signs, variable references and method calls alongside the original backslash case. Verify faithful output and the absence of execution side effects.

References