Open to everyone Reading, lesson 54 of 100, 2 min read
Injection
Data that becomes code
Injection happens when an application builds a command or query by gluing user input into it, and the input changes the meaning of the command.
SQL injection
Imagine sign-in code that builds a database query like this:
SELECT * FROM users WHERE email = '<what the user typed>'If the user types an ordinary email, all is well. But characters such as a single quote can end the text early and add new instructions to the query. Depending on the database and the code, an attacker might bypass sign-in, read other users' data or change records. It has caused some of the largest data breaches in history.
The fix: keep data and code apart
Use parameterised queries (also called prepared statements). The query is sent with placeholders, and the data is sent separately, so the database never treats it as part of the command:
$stmt = $pdo->prepare('SELECT * FROM users WHERE email = ?');
$stmt->execute([$email]);Whatever the user types, it is only ever compared as text. This one habit prevents SQL injection.
Supporting controls:
- Least privilege for the database account the application uses.
- Input validation: check that an email looks like an email, a number is a number.
- Generic error messages: do not show database errors to visitors.
Other kinds of injection
| Kind | What is injected | Prevention |
|---|---|---|
| OS command injection | Shell commands, via input passed to system commands | Avoid calling the shell; use safe library functions with arguments passed separately |
| LDAP / NoSQL injection | Directory or document-database queries | Parameterised APIs for those systems |
| Template injection | Template code in user text | Never build templates from user input |
| Header injection | New lines in email or HTTP headers | Reject line breaks in header values |
Warning
Testing websites for injection without written permission is illegal. Practise only on deliberately vulnerable training applications in your own lab.