Tuesday, December 11, 2012

SQL Injection attack and prevention

Attack

Let’s take the case of Login System in which a person logins using his username and password. The following SQL query authorizes the user. In this query, a user can logs in if and only if there exists a row in `users` table having the `user` and `pass` value equal to the posted value.

               $user=$_POST['user'];
      $pass=$_POST['pass'];
               $chkqry=mysql_query("select `id` from `users` where `user`='".$user."' and `pass`='".$pass."'");

Suppose, if the user enters the following username and password in the Login Box fields.

                Username           :               anyword’ OR ‘a’=’a
                Password            :               anyword’ OR ‘a’=’a

Then the query is as follows,

                $chkqry=mysql_query("select `id` from `users` where `user`='anyword’ OR ‘a’=’a’ and `pass`='anyword’ OR ‘a’=’a’”);

This is always true and returns all the rows of the table results in logging of the user.
This is SQL Injection.

Prevention

The function mysql_real_escape_string() in PHP escapes the special characters like quotes (), double-quotes() etc. That is the function converts the characters as follows:

     ‘    ->   \’
     “    ->   \”

This is best method to prevent SQL Injection Vulnerability.

No comments:

Post a Comment