SQL Injection

Risk type:HIGH


SQL Injection is used to get private information from Web server's database (dumping the database contents, like passwords or credit card numbers, to the attacker), remote code execution and even total system compromise.

Using an unverified/unsanitized user input the attacker injects malicious SQL code through the web form entry field, which is then executed by an SQL application.


Vulnerable code:

<form action="sql.php" method="POST" />
<p>Name: <input type="text" name="name" />
<input type="submit" value="Add Comment" />
<?php $query = "SELECT * FROM users WHERE username = '{$_POST['username']}'";
$result = mysql_query($query); ?>

When submitting a non-malicious string (“John”) the query becomes:

$query = "SELECT * FROM users WHERE username='John'";

A malicious SQL injection...

$query = "SELECT * FROM users WHERE username='' OR '1=1'";

...could get this code to be executed on the SQL application. As the "OR" condition is always true, the mysql_query function returns records from the database.


  • Correct filtering (escaping) of string literal escape characters in SQL statements, like single quote ('), double quote ("), backslash (\) and NUL (the NULL byte).
  • Checking parameters for valid representation for the give type (integer, float or boolean).
  • When validating data on the client side, also validate all data on the server side.
  • Correct database permissions on logon, which restricts web application or user access to unnecessary data.

Further reading: