DML School of Technology
Menu

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:

php
$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

KindWhat is injectedPrevention
OS command injectionShell commands, via input passed to system commandsAvoid calling the shell; use safe library functions with arguments passed separately
LDAP / NoSQL injectionDirectory or document-database queriesParameterised APIs for those systems
Template injectionTemplate code in user textNever build templates from user input
Header injectionNew lines in email or HTTP headersReject 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.