In this tutorial we will take a look atSQL Injection, how to attack using sql injection and how we can prevent ourselves form it. Firstly we see what is it after all, SQL Injection is subset of the an unverified/unsanitized user input vulnerability ("buffer overflows" are a different subset), and the idea is to convince the application to run SQL code that was not intended. If the application is creating SQL strings naively on the fly and then running them, it's straightforward to create some real surprises. In this tutorial we will discuss only one and most common type to attack that is done usually on the login.
Typically the code we used for loging a user is some what similar to the following.
i find it easy to implement... do you?
Typically the code we used for loging a user is some what similar to the following.
// ... $username=$_REQUEST["username"]; $password=$_REQUEST["password"]; $query="select * from user where username='$username' AND password='$password'"; $result=mysql_query($query); $count=$mysql_num_rows($result); if($count==1){ // after login process goes here } if($coun!=1){ // Declined user process goes here } // ...this work perfectly fine until an invader comes and tried to run credentials like
User Name : admin Password : FAKE_PASSWORD' OR 'x'='xif the above credentials are passed the query rendered will be
select * from user where username='admin' AND password='FAKE_PASSWORD' OR 'x'='x'which is a legal SQL query it also satisfy our login criteria and hence an ilegimate user will be granted access.
Prevention
if we want to defend ourselves from this type of attack we have many solution available like$query = sprintf("SELECT * FROM `user` WHERE username='%s' AND password='%s'", mysql_real_escape_string($username), mysql_real_escape_string($password)); mysql_query($query);or you can use Object Relation Mapping for may be Prepared statement... but i use the following code to prevent myself from it.
// ... $username=$_REQUEST["username"]; $password=md5(md5($_REQUEST["password"])); // Double MD5 are hard to find $query="select * from user where username='$username'"; $result=mysql_query($query); $obj=mysql_fetch_object($result); $dbPass=$obj->Password; // password stored with Double MD5 if($dbPass==$password){ // after login process goes here } else{ // Declined user process goes here } // ...in my case i don't send password to the database just fetch the password and compare it.
i find it easy to implement... do you?
1 comments:
Thank you very much!!! I was aware of SQL Injection attacks. But didn't know how it is exactly done. Thanks for explaning it and also telling the methods to prevent it. Cheers!!!
Post a Comment