Description
Request values inserted into SQL text can be interpreted as query syntax. Even when writing raw SQL, pass the statement and its values separately to the execution API.
Potential impact
Changed query conditions can bypass access checks or expose records. Writes, deletion, service disruption or operating-system commands depend on the database’s features and the account’s permissions.
Remediation
- Use your driver’s unquoted placeholders, such as
?,%s,%(name)sor:name. Bind numeric values after conversion as well. - Prefer SQLAlchemy Core or ORM expressions. For textual SQL, bind values to a fixed
text()template or use the driver’s parameter style withexec_driver_sql(). In Django, prefer the ORM and passparamstoManager.raw()or cursor calls. Peewee’sexecute_sql()and pandas’read_sql_query()also takeparams. - Select tables and columns from an allow-list in code. Compose identifiers with an API such as
psycopg.sql.Identifierwhen needed. Map sort directions to fixed choices and limit the database account’s privileges.
Examples
Before
python
import sqlite3
from flask import request
def find_users():
keyword = request.args.get("q", "")
sort_column = request.args.get("sort", "id")
with sqlite3.connect("app.db") as connection:
cursor = connection.cursor()
# Both the value and identifier are inserted directly into SQL text.
sql = (
"SELECT id, name, created_at FROM users "
f"WHERE name LIKE '%{keyword}%' ORDER BY {sort_column} DESC"
)
return cursor.execute(sql).fetchall()
After
python
import sqlite3
from flask import request
def find_users():
keyword = request.args.get("q", "")
choice = request.args.get("sort", "id")
# Input selects a branch; SQL identifiers come from fixed code literals.
if choice == "name":
sort_column = "name"
elif choice == "created_at":
sort_column = "created_at"
else:
sort_column = "id"
# SQLite's ? placeholders are for values only.
sql = (
"SELECT id, name, created_at FROM users "
"WHERE name LIKE ? "
f"ORDER BY {sort_column} DESC"
)
with sqlite3.connect("app.db") as connection:
cursor = connection.cursor()
return cursor.execute(sql, (f"%{keyword}%",)).fetchall()
SQLite receives the search pattern in the second argument to execute(). The sort column comes from code, with id as the default for unrecognized choices.
Implementation considerations
Keep SQL and values separate through the final call, including inside custom wrappers. If an API accepts either a table name or a query, map table names to a fixed set and bind values in a fixed query.