SQL injection

From Citizendium
Jump to: navigation, search
This article is a stub and thus not approved.
Main Article
Related Articles  [?]
Bibliography  [?]
External Links  [?]
Citable Version  [?]
This editable Main Article is under development and subject to a disclaimer.
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.


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:


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. Many SQL injection attacks can be neutralized through the use of a Web application firewall although such a strategy merely mitigates the threat rather than fixing the underlying problem.