Show contents
Chapter 4 of 7 · 20 min
SQL injection
By the end of this chapter, you'll be able to
- Explain how typed data can become SQL code
- Recognise a vulnerable query in code
- Fix a query with parameters
- Apply the principle of least privilege to the database
A test database
All the attacks in this chapter target a small database created in your page, in memory: it belongs to you, it is the only authorised target.
import sqlite3
db = sqlite3.connect(":memory:")
db.executescript("""
CREATE TABLE accounts (name TEXT, digest TEXT, role TEXT);
INSERT INTO accounts VALUES ('awa', 'e1f4…', 'admin'), ('kofi', '9b2c…', 'member');
""")
def find(name):
query = f"SELECT name, role FROM accounts WHERE name = '{name}'"
print(query)
return db.execute(query).fetchall()
print(find("kofi"))
SELECT name, role FROM accounts WHERE name = 'kofi'
[('kofi', 'member')]
All is well… as long as the name contains no apostrophe.
The attack
import sqlite3
db = sqlite3.connect(":memory:")
db.executescript("""
CREATE TABLE accounts (name TEXT, digest TEXT, role TEXT);
INSERT INTO accounts VALUES ('awa', 'e1f4…', 'admin'), ('kofi', '9b2c…', 'member');
""")
def find(name):
query = f"SELECT name, role FROM accounts WHERE name = '{name}'"
print(query)
return db.execute(query).fetchall()
print(find("x' OR '1'='1"))
SELECT name, role FROM accounts WHERE name = 'x' OR '1'='1'
[('awa', 'admin'), ('kofi', 'member')]
The typed apostrophe closed the string the developer intended, and the rest became SQL: OR '1'='1' is always true, so the query returns all the accounts. On a login form built this way, the same trick lets you in without knowing the password. The root problem: data and code are mixed in the same string of characters.
The fix: parameterised queries
The query is written with placeholders (? in SQLite) and the values are sent separately. The database receives the structure of the query on one side, the data on the other: a piece of data can never again be interpreted as code.
import sqlite3
db = sqlite3.connect(":memory:")
db.executescript("""
CREATE TABLE accounts (name TEXT, digest TEXT, role TEXT);
INSERT INTO accounts VALUES ('awa', 'e1f4…', 'admin'), ('kofi', '9b2c…', 'member');
""")
def find(name):
return db.execute("SELECT name, role FROM accounts WHERE name = ?", (name,)).fetchall()
print(find("kofi"))
print(find("x' OR '1'='1"))
[('kofi', 'member')]
[]
The injection attempt now looks for a user whose name is, literally, x' OR '1'='1: there is none. Note the comma in (name,): parameters are sent as a tuple, even when there is only one. Every serious language and library offers this mechanism (?, %s, $1 or :name depending on the case), and ORMs such as Prisma or SQLAlchemy use it automatically.
The database looks for a name identical to the input, apostrophes included: no result, no vulnerability.
Text description of the animation
- The attacker types an apostrophe followed by SQL.
- Pasted into the string, the input mixes with the query's code.
- The condition becomes always true: the whole table is returned.
- With a parameter, the query and the data travel separately.
- The database looks for a name identical to the input, apostrophes included: no result, no vulnerability.
Limiting the damage
Security is built in layers: if a vulnerability gets through anyway, it must do as little damage as possible. This is the principle of least privilege: the account the application uses to connect to the database must only have the permissions it needs (reading and writing certain tables), never those of an administrator able to drop the whole database or read other applications' tables. And passwords are hashed: even if read, the accounts table does not reveal them.
Mini-lab: see what the database seesSQLite
Result
Click “Run”: the SQL engine (about 1 MB) will load in your browser the first time.
A fresh SQLite database is created on every run, in your browser · Ctrl/⌘ + Enter to run · Esc then Tab to leave the editor
In the second example, each apostrophe of the input is doubled: that is how SQL writes an apostrophe inside a string. The engine therefore only looks for a name, and finds none.
Your turn
Worked exercise
Worked exercise: fixing a product search
This online shop code searches for products by category and maximum price. It is vulnerable twice. Rewrite search with parameters, then show that the input "x' OR '1'='1" no longer returns anything.
def search(category, max_price):
return db.execute(f"SELECT name, price FROM products WHERE category = '{category}' AND price <= {max_price}").fetchall()
Hint 1
? placeholders and a two-element tuple, in the same order.Hint 2
Show the solution and common mistakes
import sqlite3
db = sqlite3.connect(":memory:")
db.executescript("""
CREATE TABLE products (name TEXT, category TEXT, price INTEGER);
INSERT INTO products VALUES ('Soap', 'hygiene', 1500), ('Wax print', 'textile', 8000), ('Toothpaste', 'hygiene', 900);
""")
def search(category, max_price):
return db.execute(
"SELECT name, price FROM products WHERE category = ? AND price <= ? ORDER BY price",
(category, max_price),
).fetchall()
print(search("hygiene", 2000))
print(search("x' OR '1'='1", 2000))
[('Toothpaste', 900), ('Soap', 1500)]
[]
Common mistakes:
- Only parameterising the string and leaving the number in the f-string:
price <= {max_price}stays injectable, as in the pitfall above. - Parameterising a column or table name (
ORDER BY ?): placeholders only replace values. For a sort chosen by the user, compare their input with a list of allowed columns.
Summary
- 1SQL injection happens when input is pasted into the text of a query.
- 2An apostrophe closes the intended string, and the rest of the input becomes SQL code.
- 3Parameterised queries separate the query's structure from the data: they are the only reliable fix.
- 4Home-made filters always miss a case, such as numeric values.
- 5The application's database account only has the permissions it strictly needs.
Your progress is saved on this device. Create a free account to keep your progress on all your devices.