Vulnerability class

SQL injection in Python

SQL injection is a flaw where data an attacker controls becomes part of the text of a SQL statement, so the database runs a query the developer never wrote.

CWE
CWE-89
OWASP
A05:2025 Injection
Tag
sqli, high impact
On this page

How it shows up in Python

Every Python database driver can keep a statement and its values apart, but only when the code lets it. The bug is building the statement as a string. This f-string reads naturally and is exploitable: a name of x' OR '1'='1 returns every row.

import sqlite3

def find_user(conn: sqlite3.Connection, name: str):
    cur = conn.execute(f"SELECT id, email FROM users WHERE name = '{name}'")
    return cur.fetchall()

The fix is a placeholder. The driver sends the value separately, so it never becomes SQL text:

def find_user(conn: sqlite3.Connection, name: str):
    cur = conn.execute("SELECT id, email FROM users WHERE name = ?", (name,))
    return cur.fetchall()

psycopg and mysqlclient use %s placeholders. Passing the values as the second argument to execute() is safe; formatting them into the string with the % operator is the same bug as the f-string. Frameworks have the same split. Django's ORM methods bind values for you, but raw() and extra() take SQL text, and so does SQLAlchemy's text():

User.objects.raw(f"SELECT * FROM auth_user WHERE username = '{username}'")
User.objects.extra(where=[f"last_name = '{last}'"])
session.execute(text(f"SELECT * FROM orders WHERE ref = '{ref}'"))

Each has a parameterized form:

User.objects.raw("SELECT * FROM auth_user WHERE username = %s", [username])
User.objects.filter(last_name=last)
session.execute(text("SELECT * FROM orders WHERE ref = :ref"), {"ref": ref})

Placeholders only cover values. A table name, a column name or a sort direction cannot be bound, so a request parameter that picks the ORDER BY column needs an allowlist:

SORTABLE = {"created": "created_at", "total": "amount"}
column = SORTABLE.get(request.GET.get("sort"), "created_at")
rows = conn.execute(f"SELECT * FROM orders ORDER BY {column}").fetchall()

Why it is hard to see

The variants below are hard for tools that read source code or inspect traffic, as the injected SQL only exists while the program runs.

  • Decoded inside the application. A request carries 0~~OR~~1EQ1, which contains no SQL syntax at all, and the code turns it into 0 OR 1=1 with two replace() calls before building the query. A web application firewall matching signatures in the request has nothing to match, and a static analyzer sees string replacement, not SQL.
  • Reached through an alias. run = conn.cursor().execute followed by run(sql) does not look like a call to execute() with a formatted argument, so a rule written for that shape stays quiet.
  • Split across two fields. Two request parameters that are harmless alone are joined inside the application into name = '' OR 1=1 --. No single field carries a signature.
  • Second-order. The value is stored safely today and read back next week by a report job that concatenates it into a query. No request carries the attack and no single function shows the flow.
  • No HTTP request at all. A Celery worker builds a query from a queue message. Tools scoped to the web request never see it.
  • Inside a dependency. Two severe Django SQL-injection CVEs have this shape. CVE-2024-42005 (CVSS 7.3 High per NVD; CISA rates it 9.8 Critical) let a crafted JSON key passed to QuerySet.values() or values_list() on a JSONField act as a column alias; CVE-2025-57833 (CVSS 8.1 High per NVD) did the same through FilteredRelation aliases in annotate() or alias(). Both are in Django itself, and es-python flags both, because the attacker's key reaches the SQL text whoever's code built it.

What the es-python event looks like

es-python reports when untrusted data reaches the text of a statement, at the call that sends it. The sink label depends on the library: sqlite execute for the standard sqlite3 module, the driver's own query call for the PostgreSQL, MySQL, MariaDB and Oracle drivers that ship with es-python, sql raw for Django's raw() and extra(), and sql injection for SQLAlchemy's text(), asyncpg, mysql-connector-python, aiomysql, the Cassandra driver and clickhouse-driver. Every one carries the sqli impact tag.

A value passed as a bound parameter never enters the statement text, so a correctly parameterized query produces no event. That is what makes an sqli event worth opening: attacker-controlled characters were part of the SQL the database was asked to parse. If the code compared the value against a fixed list first, the flow is harmless, and the event shows you the value, its source and the stack trace so you can judge.

The severity comes from the source and the sink. A query is one of the most damaging sinks, so the same flow is graded Critical when the data came from the network, Medium when it came from standard input or an environment variable, and Info when it came from a file only the program's owner can write. When EyalSec can prove the untrusted part could not change the statement, the event is suppressed: kept, but out of the default view. Second-order flows appear when the db_rows source is on, which marks values read back from the database.

Under a Raise rule on the label, the program gets a RuntimeError before the statement reaches the database.

How to fix and prevent it

  1. Pass every value as a parameter. Keep f-strings, %, + and format() out of SQL.
  2. Allowlist identifiers: map user choices to column and table names you wrote.
  3. Treat raw(), extra(), RawSQL, text() and cursor.execute() with a computed string as review points, and search the codebase for them.
  4. Give the application a database account that can only do what it needs, so a successful injection reaches less.
  5. Keep Django, SQLAlchemy and your drivers current; Django's security team fixed both CVEs above.
  6. Run es-python in Report mode with the socket source on to see which statements receive request data, then add Raise rules for the ones you understand.

Classification

SQL injection is CWE-89, Improper Neutralization of Special Elements used in an SQL Command. OWASP lists CWE-89 under A05:2025 Injection in the Top 10 for 2025.

Questions people ask

The questions that come up on forums and in reviews about this class, each answered in a few sentences.

Does the Django ORM protect me from SQL injection?

For values, yes: filter(), get() and the other query methods bind values as parameters, so a value never becomes SQL text. The escape hatches take SQL text you wrote, so raw(), extra(), RawSQL and cursor.execute() are safe only when the values travel in params, and identifiers such as column names and sort keys need an allowlist because no parameter can carry them. Two Django CVEs, CVE-2024-42005 and CVE-2025-57833, were alias injections inside the framework itself, which Django's security team fixed promptly.

Can a WAF stop SQL injection in a Python app?

A WAF stops the injection attempts it recognises in the request, a useful first layer. Its decision is made on the bytes on the wire, before the application decodes a payload, joins two harmless fields or reads a queue. es-python adds a check at the query itself, with the value that really reached it, whatever route it took.

How do I detect SQL injection in a running Django or Flask app?

Run the application with es-python in Report mode with the network source on, and every statement that receives request data appears on the dashboard with the value, its source and the stack trace. A correctly parameterized query never fires, so the list is exactly the set of statements built from request text. Once you have judged them, a Raise rule stops the ones you want blocked before the statement reaches the database.

Watch for SQL injection in your own code

es-python runs your Python application unchanged and reports when untrusted data reaches the operation, with where the data came from and the line that used it. Ask to see it on your own application.

EyalSec Pricing Docs Security Research Vulnerabilities Play Security glossary About Contact עברית Login Get started Protect my Python app