Find the bug · #70 · Errors and security Medium Python
Logging in as anyone
A security tester logs in as the admin without knowing the password.
On this page
The report
During a security review, a tester logged in as admin without the password, by typing a strange-looking username.
The code
Read it first: what should it do? Then click the line where you think the bug is.
import sqlite3
def find_user(conn, username, password_hash):
"""The user with this name and password hash, or None."""
query = f"SELECT name FROM users WHERE name = '{username}' AND password_hash = '{password_hash}'"
return conn.execute(query).fetchone()Read it, then pick a line.
Put the tester’s username, admin' --, into the query by hand. What does the database see?
What it prints
Running it on a small example prints the output on the left. It should print the output on the right.
conn = sqlite3.connect(":memory:")
conn.execute("CREATE TABLE users (name TEXT, password_hash TEXT)")
conn.execute("INSERT INTO users VALUES ('admin', 'x9f2'), ('asha', 'b71c')")
print(find_user(conn, "asha", "b71c"))
print(find_user(conn, "admin' --", "anything"))It prints
('asha',)
('admin',)It should print
('asha',)
NoneShow the answer: the bug, the fix, and how you’d find it
The bug (lines 5, 6)
Line 5 pastes the username straight into the SQL text. A username of admin' -- closes the quote and starts an SQL comment, so the query becomes … WHERE name = 'admin' --' AND password_hash = …: the password check is commented out. This is SQL injection. Pass values as parameters (?) so they can never become part of the SQL.
The fix
2 3def find_user(conn, username, password_hash):4 """The user with this name and password hash, or None."""5 query = f"SELECT name FROM users WHERE name = '{username}' AND password_hash = '{password_hash}'"6 return conn.execute(query).fetchone()5 query = "SELECT name FROM users WHERE name = ? AND password_hash = ?"6 return conn.execute(query, (username, password_hash)).fetchone()How you’d find it
- Reproduce with the tester’s input: you get the admin row back with a wrong password.
- Print the final query string: the password condition sits after
--, a comment. - Any user input formatted into SQL can do this. The fix isn’t escaping quotes by hand; it’s parameters.
The test that catches it
It fails on the code above and passes once it’s fixed. Keep it, so the bug can’t come back.
conn = sqlite3.connect(":memory:")
conn.execute("CREATE TABLE users (name TEXT, password_hash TEXT)")
conn.execute("INSERT INTO users VALUES ('admin', 'x9f2')")
assert find_user(conn, "admin' --", "nope") is None
assert find_user(conn, "' OR '1'='1", "' OR '1'='1") is None
assert find_user(conn, "admin", "x9f2") == ("admin",)Where else this bites
- The same in any language: string-built SQL, ORMs’ “raw” query functions, search filters.
- Command injection, when user input goes into a shell command.