code–data–code–HOW THE DATABASE READS IT1import html, sqlite32db = sqlite3.connect(":memory:")3db.execute("CREATE TABLE users (name TEXT)")4name = "O'Brien" # typed into a form5q = "SELECT name FROM users WHERE name = "6bad = q + "'" + name + "'" # the mistake7rows = db.execute(q + "?", (name,)).fetchall()8if not rows:9 print("No results for", html.escape(name))→ No results for O'Brien
Back: the visitor's browser, the web app and how the database reads the query (code | data | code)Front: the app's Python and the databaseTokens: the name, the query, an error, the separate value, the reply page and a refused requestA visitor named O'Brien searches a member list. Gluing her name into the SQL text lets the apostrophe end the quoted text early, so part of the name is read as code: a syntax error here, SQL injection in general. A parameterized query sends the code and the value apart, so the value stays data. Escaping the reply keeps input from becoming page code, and the server checks permission on every request.

Untrusted input

  1. A web app has three parts. The browser shows pages and sends requests. The app is code on a server that answers them. The database stores the data. This app lets visitors search its member list by name.

Injection: mistake and fix

Output, access and design

What happens

;; step 1/8 · parts
browser    shows pages, sends requests
web app    code on a server (Python here)
database   stores the data (SQLite here)
example    search members.example by name

The row is a picture of the idea, not of how SQLite really parses: the database splits the whole text into tokens. What it shows is true: with glued text, part of the name ends up outside the quotes and is read as SQL. Real apps seldom call html.escape by hand: template engines such as Jinja2 and frameworks such as Django escape output by default, and database libraries make parameters easy. CISA asks for exactly that: safe by default.