SQL Injection

SQL injection is when malformed user input is used directly and deliberately in an SQL query, in a way that allows the attacker to manipulate the query. This means that an attacker could delete portions of your database, make himself an admin account, etc — the possibilities are endless. Sites that use databases as a backend to store their data and using queries to insert and select data from it are often vulnerable to this form of SQL injection attacks.

One of the most common vulnerabilities is when logging in to a site. Take this example:

$username = $_POST[‘username’];
$password = $_POST[‘password’];
$result = mysql_query(“SELECT * FROM usersTbl WHERE username = ‘$username’ AND password = ‘$password'”);

if ( mysql_num_rows ($result) > 0)
// logged in

This script is vulnerable to an obvious SQL injection attack. If the attacker enters a valid username in the username field, “rob”, and the following in the password field:

‘ OR 1=1’

The resulting query will look like this:

SELECT * FROM site_users WHERE username = ‘rob’ AND password = ” OR 1=1

Since the last criteria will always be true, when 1 is equal to 1, the user will be able to log in as rob without knowing rob’s password.

How to prevent SQL injection

As with XSS attacks, you must never trust user input. The best way of cleaning user input is using the following PHP’s built in functions:

  • mysql_real_escape_string() – Used to escape characters such as ‘, ” and others, making them useless in “breaking out” of a quoted string as in the above example.
  • intval() – Used to escape on inputted numbers to ensure it is numeric.