Cybersecurity Topics: Threats, Defences and Careers · Course book
Chapter 9: SQL Injection
SQL injection is one of the oldest and best-understood web vulnerabilities, and yet it continues to cause serious data breaches, because the mistake behind it is easy to make and the damage when it is exploited can be enormous. The flaw arises when an application builds a database command by joining fixed text with input supplied by a user. If that input contains the right characters, it stops being treated as data and starts being treated as part of the command, allowing an attacker to read, change or delete records they should never reach. This chapter explains how databases and SQL work, exactly how an injection happens using a simple login example, the main varieties of SQL injection, why the impact can be so severe, and, most importantly, the reliable techniques that prevent it completely. All examples are for understanding and defence; testing for SQL injection on systems you do not own or have written permission to test is illegal.
Databases, SQL and how applications use them
Most web applications store their data in a relational database, which organises information into tables of rows and columns, rather like a set of linked spreadsheets. A shop might have a table of customers, a table of products and a table of orders. Applications talk to the database using SQL (Structured Query Language), a language for asking questions of the data and changing it. A query to find a customer by email address might read:
SELECT name, address FROM customers WHERE email = '[email protected]';
The words in capitals are SQL keywords; customers is the table; and the text between single quotes is a string literal, a piece of data. The quotes mark where the data starts and stops. This boundary between command and data is exactly what SQL injection attacks.
How an injection happens
Consider a login form with a username and password. A careless program might create its database query by pasting the user's input directly into a string of SQL text, like this:
query = "SELECT * FROM users WHERE username = '" + username +
"' AND password = '" + password + "'";
For a normal user named alex, the resulting query is harmless. But suppose someone types the following into the username box: admin' --. The program builds:
SELECT * FROM users WHERE username = 'admin' --' AND password = ''
The single quote typed by the attacker closes the string early. In many database systems, two dashes begin a comment, so everything after them, including the password check, is ignored. The database now simply looks for the user called admin, and the attacker may be logged in as the administrator without knowing the password. A different input, such as one that adds a condition that is always true, could return every row in the table.
Varieties of SQL injection
Attacks are grouped by how the attacker obtains results from the database.
| Type | How results are obtained | What a defender may notice |
|---|---|---|
| In-band: error-based | Database error messages shown on the page reveal information | Unusual errors in logs; detailed error pages |
| In-band: union-based | Extra query results are combined with the normal results and displayed | Odd characters and SQL keywords in request parameters |
| Blind: boolean | The page behaves slightly differently for true and false conditions | Large numbers of similar requests from one source |
| Blind: time-based | The attacker makes the database pause when a condition is true | Requests that take unusually long; repeated slow queries |
| Out-of-band | The database is made to send data to an outside server | Unexpected outbound connections from the database server |
In in-band attacks the results appear directly in the application's responses, which makes them fast. In blind attacks the application shows no data, but the attacker can still ask yes-or-no questions, such as "is the first letter of the administrator's password greater than M?", and infer the answer from how the page responds or how long it takes. Blind attacks are slow, but automated tools make them practical, and the number of requests they need is itself a clue for defenders.
Why the impact is so severe
A successful SQL injection can let an attacker bypass logins, read entire tables of personal data, change prices or account balances, delete records and, in some configurations, run commands on the database server itself. Because a single vulnerable form can expose a whole database, SQL injection has been behind some of the largest data breaches on record, involving millions of payment cards and customer accounts. The impact touches every part of the CIA triad: stolen records break confidentiality, altered records break integrity and deleted tables break availability. Organisations may also face regulatory fines and must notify affected customers.
Injection is not always immediate. In second-order SQL injection, malicious input is stored safely at first, for example as a username at registration, and only causes harm later, when another part of the application retrieves it and pastes it into a new query without protection. This is why every query must be protected, including those that use data the application itself stored, since "it came from our own database" does not make data trustworthy. The same underlying mistake, mixing untrusted data into something that will be interpreted as instructions, also appears outside SQL. Command injection happens when user input is inserted into an operating system command, and similar injection flaws affect other database languages, template systems and even prompts given to AI models. Recognising the shared pattern, data crossing into a place where it can become code, helps developers spot new variations rather than memorising separate rules for each technology.
Preventing SQL injection
The good news is that SQL injection is entirely preventable. The primary defence is to use parameterised queries, also called prepared statements. The program sends the database a fixed SQL command containing placeholders, and sends the user's input separately as parameters. The database never interprets the parameters as SQL, whatever characters they contain. In many languages the safe version of the login query looks something like this:
query = "SELECT * FROM users WHERE username = ? AND password_hash = ?";
results = database.execute(query, [username, hash(password)]);
Notice also that a well-designed system compares a password hash, never the password itself. Most modern frameworks and object-relational mapping libraries build parameterised queries automatically, which is one reason to use them rather than building SQL text by hand. Danger returns whenever developers bypass these tools to assemble raw queries from strings.
Further layers reduce risk if a mistake slips through. Input validation rejects input that does not match what is expected: an order number should contain only digits, a date should be a valid date. Least privilege means the application's database account has only the permissions it needs; a public search page should use an account that can read product data but not alter user tables or drop the database. Generic error messages shown to users, with details kept in protected logs, deny attackers the clues used in error-based injection. A web application firewall can block many common attack patterns, and monitoring can flag the bursts of unusual requests typical of automated tools. Regular code review, automated static analysis and authorised penetration testing help find vulnerable code before attackers do. None of these extra layers replaces parameterised queries; they are a safety net, not the main defence.
Even parameterised queries have a limit worth knowing. Placeholders can stand only for data values, not for structural parts of a query such as table names, column names or the direction of a sort. If an application lets users choose which column to sort by, the program should check the user's choice against a fixed list of permitted column names, never paste it in directly.
Check your understanding
- Explain, using the login example, why a single quote character in user input can change the meaning of an SQL command.
- What is the role of the two dashes in the example input
admin' --? - Distinguish between in-band and blind SQL injection.
- For a 20-character secret drawn from 64 possible characters, calculate the approximate number of requests needed with one-at-a-time guessing and with binary search.
- Explain why parameterised queries prevent SQL injection completely, while input validation alone does not.
- Describe how least privilege for the database account limits the damage of an SQL injection on a product search page.
This course book is available to read online only at chrysolites.org.