Static analysis (SAST) check · Python

SQL injection (Python)

A SQL statement is built by concatenating a variable into the query string.

Why it matters

If the variable carries user input, this is a SQL injection: an attacker can supply input that changes the statement's structure.

How to fix it

Use a parameterised query (pass values through the DB-API's own placeholder syntax) instead of building SQL with string concatenation or an f-string.

Example

The rule's own test fixtures, verbatim: the test suite requires the rule to report the first and not the second.

Vulnerable: reported (Python)
def lookup(conn, user_id):
    cursor = conn.cursor()
    cursor.execute("SELECT * FROM users WHERE id = " + user_id)
    return cursor.fetchall()
Fixed: not reported (Python)
def lookup(conn, user_id):
    cursor = conn.cursor()
    cursor.execute("SELECT * FROM users WHERE id = ?", (user_id,))
    return cursor.fetchall()

What TrustIvan reads

Runs on repository scans of Python source once static analysis is turned on (SAST_RULES and the separately built analyzer image); it is off by default.

Weakness classes and references

Terms: SAST (static application security testing), Taint analysis, CWE (Common Weakness Enumeration), OWASP Top 10

All static analysis (SAST) checks · The whole catalogue · How this works in TrustIvan · Documentation

See TrustIvan on your own estate.

Book thirty minutes with an engineer and bring an image, a repository or a cloud account, or start free on the hosted service.