Skip to content

python.sql_injection

Correctness Critical Common in Incidents

Detects SQL queries that use string interpolation (f-strings, .format(), %) instead of parameterized queries, which can lead to SQL injection vulnerabilities.

SQL injection is one of the most dangerous vulnerabilities. An attacker can:

  • Steal data — Dump entire database contents
  • Modify data — Update or delete records
  • Bypass authentication — Log in as any user
  • Execute commands — In some configurations, run system commands

A single unescaped input can compromise your entire system.

# ❌ Before (vulnerable)
query = f"SELECT * FROM users WHERE id = {user_id}"
cursor.execute(query)

If user_id is "1; DROP TABLE users; --", you’ve just lost your users table.

# ✅ After (safe)
query = "SELECT * FROM users WHERE id = %s"
cursor.execute(query, (user_id,))

Parameterized queries escape inputs automatically. The database treats them as data, not code.

  • f-strings containing SQL keywords (SELECT, INSERT, UPDATE, DELETE)
  • .format() calls in SQL query strings
  • % string formatting in query strings
  • String concatenation (+) building SQL queries

Unfault can generate patches that convert interpolated queries to parameterized form, extracting variables into the parameter tuple when the transformation is unambiguous.