SQL in Applications: Parameterized Queries and SQL Injection
How real programs send SQL safely -- and how attackers break the ones that do it wrong
- describe how an application connects to a database and sends SQL,
- explain why building queries by string concatenation is dangerous,
- read the anatomy of a SQL injection attack (login bypass and UNION data theft),
- write a parameterized query / prepared statement that neutralises the attack,
- apply least privilege so a compromised query does as little damage as possible.
1. How an application sends SQL
You have been running SQL by hand in a client. A web or mobile app does the same thing, just programmatically. It opens a connection to the database through a driver (a library such as mysql2 for Node.js, JDBC for Java, or psycopg for Python), sends a query as text, and reads back the rows.
The database has no idea a "user" exists. It receives a string, parses it into a query, runs it, and returns a result set. That is the crux of the whole topic: the database trusts whatever SQL text it is handed. If your code lets an outsider influence that text, the outsider is effectively writing SQL on your server.
Everything below uses one small shop database. Let us build it once.