TExcelTAD
Home › Web Application Security: OWASP Top 10, APIs & Authentication › Parameterised Queries, ORMs and Least Privilege

Parameterised Queries, ORMs and Least Privilege

The three previous lessons showed SQL injection reading data in-band, leaking it bit by bit, and arriving through stored values. They all share one fix, and the fix is not clever: keep SQL text and data apart, everywhere. But "everywhere" includes ORMs' raw-SQL escape hatches, dynamic sorting, IN lists and reports, and a fix that has to be perfect in thousands of queries benefits from a second layer that limits the damage of the one that isn't. This lesson covers the fix in its real-world forms (drivers, ORMs, query builders), the second layer (the database's own permissions), and the test that keeps it fixed.

Definitions

  • Parameterised query / prepared statement: SQL with placeholders, values passed separately. Placeholder styles: ? (SQLite, JDBC), %s (psycopg, MySQL drivers: not Python's % operator), :name, $1 (PostgreSQL), @p (SQL Server).
  • ORM (SQLAlchemy, Django ORM, Hibernate, Entity Framework, ActiveRecord, Prisma): builds parameterised SQL from method calls. Safe by default; unsafe in raw APIs: text() with f-strings, .raw(), .extra(), whereRaw, $queryRawUnsafe, FromSqlRaw with interpolation.
  • Least privilege: each application component connects with an account that can do only what it needs; read-only replicas for search, no DDL, no access to other schemas, no file or OS functions.
  • Defence in depth: input validation, generic errors, WAF rules and monitoring around the real fix.

Safe and unsafe forms in common stacks

Stack Safe Unsafe
Python DB-API cur.execute("… WHERE id = %s", (uid,)) cur.execute("… WHERE id = %s" % uid), f-strings
SQLAlchemy select(User).where(User.email == email), text("… = :e").bindparams(e=email) text(f"… = '{email}'")
Django User.objects.filter(email=email), raw("… = %s", [email]) raw(f"… = '{email}'"), .extra(where=[f"…{x}"])
Java JDBC PreparedStatement ps = c.prepareStatement("… = ?"); ps.setString(1, email) stmt.executeQuery("… = '" + email + "'")
Node (pg) client.query("… = $1", [email]) client.query(`… = '${email}'`)
.NET EF Core FromSqlInterpolated(
quot;… = {email}")
(parameterises)
FromSqlRaw("… = '" + email + "'")

A query helper that can't be misused easily

Most injection in modern code comes from the places parameters don't reach: column names, sort order, IN lists of variable length. A small helper can make the safe way the easy way. The example builds a filtered, sorted product query from untrusted input and runs a list of hostile inputs through it.

python · try it yourself
import sqlite3

db = sqlite3.connect(":memory:")
db.executescript("""
CREATE TABLE products (id INTEGER PRIMARY KEY, name TEXT, category TEXT, price REAL);
INSERT INTO products (name, category, price) VALUES
  ('Green Tea', 'drinks', 4.5), ('Tea Pot', 'kitchen', 19.0), ('Coffee', 'drinks', 7.0), ('Mug', 'kitchen', 6.0);
""")

SORTABLE = {"name": "name", "price": "price"}           # identifiers: allow-list only
DIRECTIONS = {"asc": "ASC", "desc": "DESC"}

def find_products(categories, sort="name", direction="asc", limit=10):
    if not categories or len(categories) > 20:
        raise ValueError("1 to 20 categories")
    order = SORTABLE.get(sort)
    way = DIRECTIONS.get(direction)
    if order is None or way is None:
        raise ValueError("bad sort")
    limit = int(limit)
    if not 1 <= limit <= 100:
        raise ValueError("bad limit")
    placeholders = ", ".join("?" for _ in categories)    # one ? per value: the IN list is still bound
    sql = f"SELECT name, price FROM products WHERE category IN ({placeholders}) ORDER BY {order} {way} LIMIT ?"
    return db.execute(sql, (*categories, limit)).fetchall()

print(find_products(["drinks", "kitchen"], sort="price", direction="desc", limit=3))
for bad in [dict(categories=["drinks') OR 1=1 --"]),
            dict(categories=["drinks"], sort="(SELECT price FROM products LIMIT 1)"),
            dict(categories=["drinks"], direction="; DROP TABLE products"),
            dict(categories=["drinks"], limit="1 UNION SELECT 1,2")]:
    try:
        print("ok:", find_products(**bad))
    except ValueError as e:
        print("refused:", e)
print("table still there:", db.execute("SELECT COUNT(*) FROM products").fetchone()[0], "rows")
[('Tea Pot', 19.0), ('Coffee', 7.0), ('Mug', 6.0)]
ok: []
refused: bad sort
refused: bad sort
refused: invalid literal for int() with base 10: '1 UNION SELECT 1,2'
table still there: 4 rows

The IN list payload became a category name that matches nothing; the sort, direction and limit payloads never reached SQL because each has an allow-list or a type. The f-string in find_products is safe only because every piece it pastes comes from a fixed dictionary or is a string of ? characters; that is the one acceptable form of building SQL text, and it should live in one reviewed helper.

The second layer: what the account may do

Even with a missed query, the damage depends on the database account. SQLite has no users, but sqlite3 lets a connection install an authorizer callback that the engine consults for every table and column a statement touches, which is a good model of database permissions. The "search" connection may read products and nothing else.

python · try it yourself
import sqlite3

db = sqlite3.connect(":memory:")
db.executescript("""
CREATE TABLE products (name TEXT, price REAL);
CREATE TABLE users (email TEXT, pw_hash TEXT);
INSERT INTO products VALUES ('Green Tea', 4.5);
INSERT INTO users VALUES ('admin@lab.test', '$argon2id$lab-only');
""")

def search_account(action, arg1, arg2, dbname, source):
    if action == sqlite3.SQLITE_SELECT:
        return sqlite3.SQLITE_OK
    if action == sqlite3.SQLITE_READ and arg1 == "products":
        return sqlite3.SQLITE_OK
    return sqlite3.SQLITE_DENY

db.set_authorizer(search_account)
q = "x' UNION SELECT email, pw_hash FROM users --"       # a query someone forgot to parameterise
for sql in [f"SELECT name, price FROM products WHERE name = '{q}'",
            "SELECT name, price FROM products",
            "DELETE FROM products"]:
    try:
        print("ok:    ", db.execute(sql).fetchall())
    except sqlite3.DatabaseError as e:
        print("denied:", e)
denied: access to users.email is prohibited
ok:     [('Green Tea', 4.5)]
denied: not authorized

The injected UNION reached SQL, but the engine refused to read users, and the account can't delete. In PostgreSQL or MySQL the same idea is a role: GRANT SELECT ON products TO search_app; and nothing else, no superuser, no pg_read_server_files, no FILE privilege, no xp_cmdshell.

Keeping it fixed (detection in the pipeline)

  • Tests with payloads: a unit test that runs ["'", "' OR '1'='1", "1; DROP TABLE x", "x' UNION SELECT 1 --"] through every data-access function and asserts that results are empty or the input is refused, and that the tables are intact.
  • SAST in CI: Semgrep rules for f-strings and + inside execute, raw, text; Bandit B608; CodeQL's SQL-injection queries. Fail the build on new findings.
  • Review rule: any change that adds raw SQL gets a second reviewer.
  • Runtime: alerts on database errors from application accounts and on permission denials (a denial in production means either a bug or an attack).

Pitfalls

  • Stored procedures are not automatically safe: EXEC('SELECT … ' + @name) inside the procedure is string building.
  • "Escaping" functions (mysql_real_escape_string, addslashes) depend on character sets and quoting context; parameters don't.
  • One database account for everything, with owner rights, turns any injection into full compromise.

Practice

1. Convert session.execute(text(f"SELECT * FROM orders WHERE user_id = {uid} AND status = '{st}'")) to safe SQLAlchemy.

session.execute(text("SELECT * FROM orders WHERE user_id = :uid AND status = :st"), {"uid": uid, "st": st}), or with the ORM: select(Order).where(Order.user_id == uid, Order.status == st).

2. Which privileges should the account of a product-search service have?

SELECT on the product and category tables (or a view of them), nothing on users, orders or payments, no write, no DDL, no file or OS functions, and ideally a connection to a read-only replica.

Test yourself

Which part of a query can't be a bound parameter?

  1. A value in WHERE
  2. A LIMIT value
  3. A column name in ORDER BY
  4. An item of an IN list

In the authorizer example, why did the injected UNION fail?

  1. The quote was escaped
  2. The engine refused to read the users table for this connection
  3. UNION is not supported
  4. The query was parameterised

Which ORM call is injectable?

  1. User.objects.filter(email=e)
  2. select(User).where(User.email == e)
  3. User.objects.raw(f"SELECT * FROM users WHERE email = '{e}'")
  4. raw('... = %s', [e])