Predict the output
What do the two lines print?
import psycopg
with psycopg.connect(autocommit=True) as conn:
conn.execute("CREATE TEMP TABLE users (name text, admin bool)")
conn.execute(
"INSERT INTO users VALUES ('ana', false), ('root', true)"
)
evil = "x' OR '1'='1"
unsafe = f"SELECT count(*) FROM users WHERE name = '{evil}'"
print(conn.execute(unsafe).fetchone()) # injectable
safe = "SELECT count(*) FROM users WHERE name = %s"
print(conn.execute(safe, (evil,)).fetchone())Hint 1 of 1
What does the WHERE clause become after formatting?
Choose an answer, then open Show answer below to check it.
Show answer
Answer: A (2,) then (0,)
Correct. The f-string turns the input into OR '1'='1', matching every row; the parameter is compared as a plain string.
The f-string pastes the input into the SQL text, so the quote ends the string and OR '1'='1' becomes part of the query. A bound parameter is sent separately and compared as data.
Why not the others?
- B
(0,)then(0,). The f-string version is rewritten by the input. - C
(2,)then(2,). Parameters are never parsed as SQL. - D An error, then
(0,). The injected SQL is valid.