Lesson 05 · 35 minutes
Break and fix a query and a page with injection
- Explain why mixing data with code causes injection
- Make a string-built SQL query leak rows, then fix it with a parameterised query
- Escape untrusted text before you put it in HTML
The lab folder as it stands after this lesson. Unzip it in ~/krlab.
More
The zip holds every file that the course has printed up to here. To start this lesson with the files of the earlier lessons only, take the zip of the lesson before. Type the code yourself first: you learn more.
Scenario
A colleague adds a search box to the notes site: "show the public notes of one owner". It works in the demo. A week later a tester types a strange line into the box and gets every private note in the database. Your task is to rebuild the flaw on your own machine, see exactly how the query changed, fix it, and then fix a second query on a new table, without help.
Recall
Lesson 2. Why does the notes API check the type, the length and the pattern of the input, instead of searching for bad words?
It validates by allowing: it defines what a good value is and refuses the rest. A list of bad strings always misses one. The same idea returns in this lesson as a parameterised query.
Lesson 4. Name the three rules that fix a broken access check.
Check on every request, check the object and not only the user, and deny by default.
The idea
A program that builds a command from a fixed part (the code) and a part from the user (the data) is safe only while the data stays data. Injection happens when the data contains characters that the interpreter reads as code, so the user's text changes what the command does.
Two defences, in this order:
- Keep data apart from code. Send the command and the values by separate routes. In SQL this is a parameterised query: the query has
?marks and the driver passes the values, which the database never reads as SQL. - Encode for the place where the data lands. In HTML,
<must become<. Python'shtml.escapedoes this.
The same root flaw appears in an LLM application. The developer's instructions and the user's text are joined into one prompt, and the model cannot reliably tell which part is code and which part is data. A user, or a web page that the model reads, can write text that the model obeys as an instruction. This is prompt injection, and the course "Securing LLM applications" returns to it. There is no ? mark for a prompt, so the defence is harder: limit what the model may do, and check what it returns.
- Attacker → Web server: owner is x' OR 1=1 --
- Web server → Database: WHERE owner = 'x' OR 1=1 --'
- Database → Web server: every row, private ones too
- Web server → Attacker: the private notes leak
Worked example
1. Build a toy database and a flawed query
Create inject.py in ~/krlab/web-apis. SQL is the language that you use to talk to a database. The module sqlite3 gives Python a small database, and ":memory:" keeps it in memory only. A table has columns, and each row is one record. CREATE TABLE makes a table, INSERT adds rows and SELECT ... WHERE reads the rows that match a condition. execute runs one SQL statement, and executemany runs it once for each tuple of a list. The ? marks in the set-up are the safe way that step 3 explains. fetchall() returns the rows as a list of tuples. In SQL, -- starts a comment: the database ignores the rest of the line.
The table holds public and private notes. public_notes_bad should return only the public notes of one owner, but it joins the owner name into the SQL text.
inject.py
import sqlite3
db = sqlite3.connect(":memory:")
db.execute("CREATE TABLE notes (owner TEXT, text TEXT, public INTEGER)")
db.executemany("INSERT INTO notes VALUES (?, ?, ?)", [
("alice", "alice: shopping list", 1),
("alice", "alice: bank PIN is 4711", 0),
("bob", "bob: wifi password is hunter2", 0),
])
def public_notes_bad(owner):
sql = "SELECT text FROM notes WHERE owner = '" + owner + "' AND public = 1"
print("SQL:", sql)
return db.execute(sql).fetchall()
evil = "x' OR 1=1 --"
print(public_notes_bad("alice"))
print(public_notes_bad(evil))cd ~/krlab/web-apis
python3 inject.pySQL: SELECT text FROM notes WHERE owner = 'alice' AND public = 1
[('alice: shopping list',)]
SQL: SELECT text FROM notes WHERE owner = 'x' OR 1=1 --' AND public = 1
[('alice: shopping list',), ('alice: bank PIN is 4711',), ('bob: wifi password is hunter2',)]2. Read what happened
The input x' OR 1=1 -- closes the quote and adds a condition that is always true. The -- turns the rest of the line into a comment, so public = 1 is never checked. The query returns every row, including the private ones. The user's text became part of the code.
3. Fix it with a parameterised query
Add this function and one line to the end of inject.py. The ? mark holds the place of the value, and the value travels in a tuple, a fixed list written in round brackets. (owner,) is a tuple with one item.
def public_notes_good(owner):
sql = "SELECT text FROM notes WHERE owner = ? AND public = 1"
return db.execute(sql, (owner,)).fetchall()
print(public_notes_good(evil))[]Run the file again. The last line is an empty list. The database looked for an owner whose name is the whole string x' OR 1=1 --, and found none. The text stayed data.
4. Escape text that goes into HTML
The same flaw works for a page. If you write a note into HTML as it is, a note that holds a <script> tag becomes a script that runs in the reader's browser. This is cross-site scripting (XSS). The function html.escape changes <, >, & and quotes into safe codes such as <. Add these lines and run the file.
import html
note = "<script>alert(1)</script>"
print("<p>" + note + "</p>")
print("<p>" + html.escape(note) + "</p>")<p><script>alert(1)</script></p>
<p><script>alert(1)</script></p>The first line is a script in a page. The second shows the same text as plain words. A template engine that escapes by default does this for you, which is why you should use one.
5. The finished file
This is the whole file as it stands after the steps above. The lab files of the course hold it.
The finished file: inject.py
inject.py
import sqlite3
db = sqlite3.connect(":memory:")
db.execute("CREATE TABLE notes (owner TEXT, text TEXT, public INTEGER)")
db.executemany("INSERT INTO notes VALUES (?, ?, ?)", [
("alice", "alice: shopping list", 1),
("alice", "alice: bank PIN is 4711", 0),
("bob", "bob: wifi password is hunter2", 0),
])
def public_notes_bad(owner):
sql = "SELECT text FROM notes WHERE owner = '" + owner + "' AND public = 1"
print("SQL:", sql)
return db.execute(sql).fetchall()
evil = "x' OR 1=1 --"
print(public_notes_bad("alice"))
print(public_notes_bad(evil))
def public_notes_good(owner):
sql = "SELECT text FROM notes WHERE owner = ? AND public = 1"
return db.execute(sql, (owner,)).fetchall()
print(public_notes_good(evil))
import html
note = "<script>alert(1)</script>"
print("<p>" + note + "</p>")
print("<p>" + html.escape(note) + "</p>")Your turn
A second table needs the same treatment. Write a new file inject2.py. There are no steps here: reuse what you learned in steps 1 to 4.
- Make an in-memory database with a table
usersthat has the columnsnameandrole, and three rows:carolis aneditor,daveis anadmin,erinis aviewer. - Write
find_user_bad(name), which joins the name into aSELECT role FROM users WHERE name = '...'query, andfind_user_good(name), which uses a?mark. - Call both with the text
x' OR '1'='1and count the rows that each returns. Callfind_user_good("dave")and read the role. Then runhtml.escapeon the text<b>hi</b>and count the characters of the result withlen().
Last, write down in one sentence why the attack text does not work in the second function.
Check yourself
Why is it not enough to remove the quote character from the input?
Quotes are one way out of the data. Other inputs work in other places, such as a number field with no quotes, or a different encoding. The robust fix is to stop joining data into code at all.
A query needs a column name that the user chooses (for sorting). Can you use a "?" for it?
No. Placeholders carry values, not names of tables or columns. Check the name against a fixed list of allowed names and put only a name from the list into the SQL.
What is the common flaw in SQL injection and prompt injection?
In both, trusted instructions and untrusted text are joined into one string that an interpreter reads. SQL has a way to separate them (parameters). A language model has no reliable one yet.
Field notes
- OWASP Top 10 lists "Injection" (it includes cross-site scripting since the 2021 edition). Parameterised queries are the first defence, and an input check is a second layer.
- The
sqlite3module runs one statement for eachexecute, so the "stacked query" trick fails here. Other drivers allow it. Do not rely on a driver feature as your defence. - Use the least privilege in the database: the account that your web app uses should not own the tables or run
DROP. An injection then does less harm. - Escape for the context. HTML text, an HTML attribute, a URL, JavaScript and CSS each need a different encoding. A Content-Security-Policy header adds a second layer against injected scripts.
- An ORM is safe only while you use its query methods. A raw string passed into
.raw()ortext()has the same flaw.