TExcelTAD
Home › Cybersecurity › SQL Injection & Parameterized Queries

SQL Injection & Parameterized Queries

SQL injection happens when user input is pasted into the text of a SQL statement, so the input can change the structure of the query instead of just supplying a value. It has caused some of the largest data breaches ever, and it is entirely preventable with one habit: parameterized queries.

The root cause

Code and data travel in the same string. If you build a query with string formatting, the database can't tell which parts you wrote and which parts the user typed. Here is a minimal, local demonstration with an in-memory SQLite database, immediately followed by the fix:

python · try it yourself
import sqlite3

db = sqlite3.connect(":memory:")
db.execute("CREATE TABLE users (name TEXT, email TEXT)")
db.executemany("INSERT INTO users VALUES (?, ?)",
               [("alice", "alice@example.com"), ("bob", "bob@example.com")])

def find_user_vulnerable(name):
    query = f"SELECT name, email FROM users WHERE name = '{name}'"   # DON'T
    print("  SQL:", query)
    return db.execute(query).fetchall()

print(find_user_vulnerable("alice"))
print(find_user_vulnerable("x' OR '1'='1"))
  SQL: SELECT name, email FROM users WHERE name = 'alice'
[('alice', 'alice@example.com')]
  SQL: SELECT name, email FROM users WHERE name = 'x' OR '1'='1'
[('alice', 'alice@example.com'), ('bob', 'bob@example.com')]

The second input contains a quote, which ends the string literal early; the rest becomes SQL logic that is always true, so the query returns every user. With other inputs the same flaw can read other tables, change data or bypass a login.

The fix: parameters

With a parameterized query (also called a prepared statement) the SQL text contains placeholders, and values are sent separately. The database parses the query structure first, then binds the values as pure data. No input can change the structure, whatever characters it contains:

python · try it yourself
import sqlite3

db = sqlite3.connect(":memory:")
db.execute("CREATE TABLE users (name TEXT, email TEXT)")
db.executemany("INSERT INTO users VALUES (?, ?)",
               [("alice", "alice@example.com"), ("bob", "bob@example.com"),
                ("o'brien", "ob@example.com")])

def find_user(name):
    return db.execute("SELECT name, email FROM users WHERE name = ?", (name,)).fetchall()

print(find_user("alice"))
print(find_user("x' OR '1'='1"))      # just a strange name: no match
print(find_user("o'brien"))           # legitimate quotes work too
[('alice', 'alice@example.com')]
[]
[("o'brien", 'ob@example.com')]

Notice the bonus: the legitimate name o'brien works without any escaping, while with string formatting it would have produced a syntax error. Parameters are both safer and more correct.

Every database library supports them, with slightly different placeholder styles:

Library Placeholder
Python sqlite3 ? or :name
Python psycopg (PostgreSQL) %s or %(name)s (passed separately, not with % formatting)
Java JDBC PreparedStatement ?
Node.js pg $1, $2
C# ADO.NET @name

ORMs (Django, SQLAlchemy, Entity Framework) use parameters automatically, but their "raw SQL" escape hatches need the same care.

Where parameters can't help: identifiers

Placeholders work for values, not for table names, column names or keywords like ASC/DESC. If a user chooses the sort column, validate it against an allow-list of known names:

python · try it yourself
import sqlite3

db = sqlite3.connect(":memory:")
db.execute("CREATE TABLE products (name TEXT, price REAL, stock INTEGER)")
db.executemany("INSERT INTO products VALUES (?, ?, ?)",
               [("Kettle", 39.0, 4), ("Mug", 8.5, 40), ("Teapot", 24.0, 12)])

SORTABLE = {"name": "name", "price": "price", "stock": "stock"}
DIRECTIONS = {"asc": "ASC", "desc": "DESC"}

def list_products(sort="name", direction="asc"):
    column = SORTABLE.get(sort)
    order = DIRECTIONS.get(direction.lower())
    if column is None or order is None:
        raise ValueError("invalid sort option")
    sql = f"SELECT name, price FROM products ORDER BY {column} {order}"   # safe: from our own map
    return db.execute(sql).fetchall()

print(list_products("price", "desc"))
try:
    list_products("price; DROP TABLE products", "asc")
except ValueError as err:
    print("rejected:", err)
[('Kettle', 39.0), ('Teapot', 24.0), ('Mug', 8.5)]
rejected: invalid sort option

The user's text never reaches the SQL: it only selects one of our own constant strings.

Defence in depth

Parameterized queries are the fix. These make an injection that slips through less damaging:

  • Least privilege: the web app's database account should only have the permissions it needs, e.g. SELECT/INSERT/UPDATE on its own tables, no DROP, no access to other databases, never the admin account.
  • Generic error messages: don't show database errors to users; they help attackers understand the query.
  • Input validation: an order ID should be an integer, an email should look like an email (next lessons).
  • Monitoring: many failed queries with syntax errors from one client is a signal worth alerting on.
  • Code review and static analysis: search for SQL built with f"...", + or .format().

Note: The same root cause, mixing untrusted data into code, appears elsewhere: command injection (os.system("ping " + host)), LDAP injection, NoSQL operator injection and template injection. The fix is always the same idea: use APIs that keep data separate from code (subprocess.run(["ping", host]) with a list, never shell=True with user input).

Go further: SQL Injection: In-Band, Error-Based and UNION runs the attacks against a sample database, then the fix, and the course continues with blind and second-order injection.

Test yourself

What is the root cause of SQL injection?

  1. Weak database passwords
  2. User input is concatenated into the SQL text and can change its structure
  3. Databases being reachable from the internet
  4. Using SQLite

Which line is safe?

  1. db.execute(f"SELECT * FROM t WHERE id = {uid}")
  2. db.execute("SELECT * FROM t WHERE id = " + uid)
  3. db.execute("SELECT * FROM t WHERE id = ?", (uid,))
  4. db.execute("SELECT * FROM t WHERE id = '%s'" % uid)

A user can choose the ORDER BY column. How should you handle it?

  1. Pass it as a ? parameter
  2. Escape quotes in it
  3. Map it through an allow-list of known column names
  4. Put it in double quotes