User-provided inputs must be sanitized before being used to generate a SQL database query. An attacker can create and use untrusted input to run query statements that read, modify, or delete database content.
1def execute_query_noncompliant(request):
2 import sqlite3
3 name = request.GET.get("name")
4 query = "SELECT * FROM Users WHERE name = " + name + ";"
5 with sqlite3.connect("example.db") as connection:
6 cursor = connection.cursor()
7 # Noncompliant: user input is used without sanitization.
8 cursor.execute(query)
9 connection.commit()
10 connection.close()
1def execute_query_compliant(request):
2 import re
3 import sqlite3
4 name = request.GET.get("name")
5 query = "SELECT * FROM Users WHERE name = "
6 + re.sub('[^a-zA-Z]+', '', name) + ";"
7 with sqlite3.connect("example.db") as connection:
8 cursor = connection.cursor()
9 # Compliant: user input is sanitized before use.
10 cursor.execute(query)
11 connection.commit()
12 connection.close()