Sunday 13 September 2009

Preventing SQL Injection with PHP

SQL injection refers to the act of someone inserting a MySQL statement to be run on your database without your knowledge. Injection usually occurs when you ask a user for input, like their name, and instead of a name they give you a MySQL statement that you will unknowingly run on your database.

From Wikiedpia.com:

SQL injection is a technique that exploits a security vulnerability occurring in the database layer of an application. The vulnerability is present when user input is either incorrectly filtered for string literal escape characters embedded in SQL statements or user input is not strongly typed and thereby unexpectedly executed. It is in fact an instance of a more general class of vulnerabilities that can occur whenever one programming or scripting language is embedded inside another.

Example



< FORM NAME="frm1" METHOD="POST" ACTION="process.php >
NAME: <INPUT NAME="name"><BR> "
" PASSWORD: <INPUT NAME="pwd">
" <INPUT TYPE="SUBMIT" VALUE="LOGIN">
</FORM>



process.php



$name = $_POST[‘name’];

$pwd = $_POST[‘pwd’];


$str_sql = "SELECT * from `tbl_users` WHERE " .
"usr_name=’" . $name . "’ AND " .
"usr_pwd=’" . $pwd . "’";
$result = mysql_query( $str_sql ) or die ( mysql_error() );

?>




The normal query is no problem.

However, the injection attack has actually made our query behave differently than we intended. By using a single quote (') they have ended the string part of our MySQL query

* usr_pwd = ' '

and then added on to our WHERE statement with an OR clause of 1 (always true).

* usr_pwd = ' ' OR 1

This OR clause of 1 will always be true!

HOW DO I PREVENT A SQL INJECTION

use mysql_real_escape_string()

so our form will be now



$name = mysql_real_escape_string( $_POST[‘name’] );
$pwd = mysql_real_escape_string( $_POST[‘pwd’] );

....................
....................




Hope This will help you.

No comments:

Post a Comment