Tuesday, December 11, 2012

Prevent MySQL injection

Prevent MySQL injection

In this post we will discuss what MySQL injection is and how important it is to prevent this attack on your mysql database. As developer it's important to check all security measure before you make your website live.

SQL injection is a code injection technique that exploits security holes in a web application. These security holes happens when user input is either incorrectly filtered for string literal escape characters embedded in SQL statements or user input is not strongly typed and unexpectedly executed. SQL commands are thus injected from the web form into the database of an application. to change the database content or dump the database information like credit card or passwords to the attacker. SQL injection is mostly known as an attack vector for websites but can be used to attack any type of SQL database.

Strings filtration

This is a main security hole that permits SQL statement to execute string without filtration. This means a user inputs a string that will be passed on to the SQL statement, resulting in database manipulation. Below is the SQL statement with a vulnerable code:

$upassword = $_POST['upassword'];
$sqlquery = mysql_query(“SELECT upassword FROM admin_user WHERE upassword = ’”. $upassword . “‘”);

The above SQL query selects the password from the table admin_user. If the user's input for the password is ‘ OR 1 = 1′, will result in the query being evaluate with an OR statement as 1 does equal 1, thus the query will return TRUE, resulting in a positive login.

After Injection: SELECT upassword FROM admin_user WHERE upassword = ” OR 1 = 1”

Protect SQL injection

You can use PHP functions like stripslashes(), addslashes(), mysql_real_escape_string() etc to make safe SQL Query.

Below is the safe SQL statement that uses PHP mysql_real_escape_string function:

$upassword = mysql_real_escape_string($_POST['upassword']);
$sqlquery = mysql_query(“SELECT upassword FROM admin_user WHERE upassword = ’”. $upassword . “‘”);

The above SQL statement is safe because it executes the query after escaping the string:

After Escaped: SELECT upassword FROM admin_user WHERE upassword = ‘\’ OR 1 = 1\”

via PHPZag by