SQL injection is old, well understood and still common. It happens when untrusted input becomes part of the SQL text, so the input can change what the query does.
The vulnerable pattern
Imagine a query built by concatenation:
def find_user_unsafe(name):
return "SELECT * FROM users WHERE name = '" + name + "'"
print(find_user_unsafe("x' OR '1'='1"))The result is SELECT * FROM users WHERE name = 'x' OR '1'='1', which returns every user. With more effort an attacker can read other tables or change data.
The fix: parameters
A parameterised query sends the SQL text and the values separately. The database treats the value strictly as data, whatever characters it contains.
import sqlite3
conn = sqlite3.connect(":memory:")
conn.execute("CREATE TABLE users (id integer, name text)")
conn.execute("INSERT INTO users VALUES (1, 'ada')")
name = "x' OR '1'='1"
rows = conn.execute("SELECT * FROM users WHERE name = ?", (name,)).fetchall()
print(rows) # [] - the quote characters are just part of the valueEvery mainstream language and ORM supports parameters. Use them for every value, including ones that look safe.
Things parameters cannot do
Placeholders work for values, not for table names, column names or sort directions. For those, choose from a fixed allow-list in your code.
-- Parameters can fill values like this:
SELECT id, name FROM users WHERE name = $1 ORDER BY created_at DESC LIMIT $2;Defence in depth
- Least privilege: the application's database account should not own the schema or be able to drop tables.
- Validate input for type and length. It is not a replacement for parameters, but it reduces the surface.
- Hide detailed errors from users, since database messages help attackers.
- Review ORM escape hatches: raw SQL fragments in ORMs are injection points when built from input.
- Test: scanners and code review should look for string-built queries.
Takeaway
Never build SQL by joining strings with user input. Use parameters for values, allow-lists for identifiers and a database account that can do only what the application needs.
Comments