2023-03-07 17:16:47 +01:00
|
|
|
== How to fix it in Python SQLite
|
|
|
|
|
|
|
|
=== Code examples
|
2022-10-24 11:09:58 +02:00
|
|
|
|
|
|
|
The following code is an example of an overly simple data retrieval function.
|
|
|
|
It is vulnerable to SQL injection because user-controlled data is inserted
|
|
|
|
directly into a query string: The application assumes that incoming data
|
|
|
|
always has a specific range of characters and ignores that some characters may
|
|
|
|
change the query logic to a malicious one.
|
|
|
|
|
|
|
|
In this particular case, the query can be exploited with the following string:
|
|
|
|
|
|
|
|
----
|
|
|
|
' OR '1'='1
|
|
|
|
----
|
|
|
|
|
|
|
|
Using the UNION clause, an attacker would also be able to perform queries against
|
|
|
|
other tables and combine the returned data within the same query result.
|
|
|
|
|
|
|
|
==== Noncompliant code example
|
|
|
|
|
|
|
|
[source,python,diff-id=1,diff-type=noncompliant]
|
|
|
|
----
|
|
|
|
from flask import request
|
|
|
|
|
|
|
|
@app.route('/example')
|
|
|
|
def get_users():
|
|
|
|
user = request.args["user"]
|
|
|
|
sql = """SELECT user FROM users WHERE user = \'%s\'"""
|
|
|
|
|
|
|
|
conn = sqlite3.connect('example')
|
|
|
|
conn.cursor().execute(sql % (user)) # Noncompliant
|
|
|
|
----
|
|
|
|
|
|
|
|
==== Compliant solution
|
|
|
|
|
|
|
|
[source,python,diff-id=1,diff-type=compliant]
|
|
|
|
----
|
|
|
|
from flask import request
|
|
|
|
|
|
|
|
@app.route('/example')
|
|
|
|
def get_users():
|
|
|
|
user = request.args["user"]
|
|
|
|
sql = """SELECT user FROM users WHERE user = (?)"""
|
|
|
|
value = (user,)
|
|
|
|
|
|
|
|
conn = sqlite3.connect('example')
|
|
|
|
conn.cursor().execute(sql, value)
|
|
|
|
----
|
|
|
|
|
|
|
|
=== How does this work?
|
|
|
|
|
2023-05-25 14:18:12 +02:00
|
|
|
include::../../common/fix/prepared-statements.adoc[]
|