Keeping databases safe with parameterised queries
Day 18 of our web security series: why mixing user input into database commands is dangerous, and the simple habit that prevents SQL injection.
Yesterday we saw that anything arriving from outside your server is untrusted input, and that validation is the first line of defence. Today we follow that input to one of the most valuable places it can reach: the database.
The problem we’re preventing is called SQL injection. It has been known for more than 25 years, it’s still in the OWASP Top 10, and it’s still behind real breaches. The good news is that the fix is simple, well supported in every language, and almost free to use.
How a database query is built
Most websites store their data in a database and talk to it in a language called SQL. When you look up an order, the application might run something like:
SELECT * FROM orders WHERE order_number = 'A1042'
The part in quotes, A1042, came from you. The rest is a command written by the developer. The database reads the whole thing as one instruction and does what it says.
Where it goes wrong
The danger appears when an application builds that instruction by gluing text together, putting whatever the user typed straight into the middle of the command.
If the input is an ordinary order number, everything works. But the database can’t tell which parts the developer wrote and which parts the user supplied. So if the input contains characters that mean something in SQL, such as quote marks, it can change the meaning of the command itself: widening a search to every row, skipping a password check, or worse.
That’s SQL injection in one sentence: user data gets treated as part of the command. We won’t go further into how attacks are written. What matters for defenders is that the root cause is always the same, and so is the cure.
Why it matters for security
A successful SQL injection can let an attacker read data they should never see, often an entire customer table, including emails, addresses and password hashes (Day 8 is why those hashes need to be slow). Depending on the setup, it can also allow changing or deleting data. It’s one of the most damaging web vulnerabilities, and because databases hold a company’s most sensitive information, a single vulnerable search box can lead to a major breach.
The fix: parameterised queries
A parameterised query (also called a prepared statement) sends the command and the data to the database separately:
SELECT * FROM orders WHERE order_number = ?
The ? is a placeholder. The application then passes the user’s input as a separate value. The database already knows the shape of the command before it sees the data, so the input can only ever be treated as a value to compare against, never as part of the instruction. Quote marks and other special characters are just characters.
In code it usually looks something like this:
db.query("SELECT * FROM orders WHERE order_number = ?", [orderNumber])
Every mainstream language and database library supports this: PHP’s PDO, Python’s database drivers, Java’s PreparedStatement, Node.js database clients, .NET’s SqlParameter and many more. The exact placeholder may be ?, $1 or :name, but the idea is identical.
ORMs help, with a caveat
Many applications use an ORM (object-relational mapper), a library that builds queries for you from code like Order.find({ number: orderNumber }). ORMs use parameters behind the scenes, which makes them safe by default.
The caveat is that most ORMs also offer a “raw query” option for unusual cases. If a developer builds a raw query by gluing strings together, the protection disappears. Search your code for raw queries and make sure they use parameters too.
Things parameters can’t cover
Placeholders work for values: the things you compare against, insert or update. They can’t be used for parts of the command’s structure, such as table names, column names or sort direction.
If users can choose, say, which column to sort by, don’t insert their choice directly. Instead, map it against a fixed allow-list in your code: if the request says price, use the column price; if it says anything not on the list, use a default. That’s validation from Day 17 doing its job.
Extra layers worth having
Parameterised queries are the main defence. These add depth:
- Least privilege for the database account. The website’s database user should only have the permissions it needs. A blog doesn’t need permission to drop tables or read other applications’ databases.
- Don’t show database errors to users. Detailed error messages help attackers understand your database. Log them for your team and show visitors a plain message.
- Validate input anyway. An order number that should be five characters shouldn’t be accepted at five thousand.
- Keep the database and its drivers updated, like any other software.
- Watch for unusual queries. Monitoring that alerts on a spike in database errors can catch probing early.
What you can do today
If you use websites:
- Use a unique password on every site. If one site’s database leaks through a flaw like this, a unique password keeps the damage there.
- Check whether your email has appeared in known breaches with our breach check tool, and change any reused passwords.
- Treat a site that shows raw database errors as a warning sign, and avoid storing sensitive information there.
If you run a website:
- Search your code for queries built by joining strings with user input, and convert every one to parameterised queries.
- Check any raw queries in your ORM code use parameters too.
- Use allow-lists for anything that can’t be parameterised, such as sort columns.
- Give your application’s database account only the permissions it needs.
- Turn off detailed database errors in production. The OWASP Query Parameterization Cheat Sheet shows the correct pattern in many languages.
Coming up next
On Day 19 we follow user input to the other place it often ends up: the web page itself. We’ll look at cross-site scripting, and why output encoding matters.