SQL injection

SQL injection is an attack mechanism used against computer applications. Using SQL injection attackers attempt to manipulate database interactions by maliciously altering queries.

SQL injection attacks succeed because developers often fail to sanitize user supplied input prior to interpolating that data in dynamic SQL queries.

Example
The following is a snippit of PHP code that is vulnerable to SQL injection $query = 'select user_id from user where username = "' . $_POST['username'] . '" and password = "' . $_POST['password'] . "'";

When executed this code should generate a SQL statement such as:

select user_id from user where username = "foo" and password = "bar"

However, if a malicious user were to craft the $_POST['username'] parameter so that its value became:

administrator"--

The SQL query would be changed so that the following statement executed:

select user_id from user where username = "administrator"--" and password = "bar"

Because the double dash (--) symbol indicates the start of a single line comment in SQL the query would ignore everything from the double dash onward. By altering the query an attacker could bypass the password check that is supposed to occur.

Defensive Strategies
By using parametrized, or prepared, statements, it is possible to type bind parameters to SQL queries, which is effective in defeating most SQL injection attacks.