All the examples mentioned in this article are tested with the following:
- PHP 5.3.3-7
- Apache/2.2.16
- Postgresql 8.4
SQL Injection Example
<html> <head><title>SQL Injection Demo</title></head> <body onload="document.getElementById('user_name').focus();" > <form name="login_form" id="login_form" method="post" action="login.php"> <table border=0 align="center" > <tr> <td colspan=5 align="center" ><font face="Century Schoolbook L" > Login Page </font></td> </tr> <tr> <td> User Name:</td><td> <input type="text" size="13" id="user_name" name="user_name" value=""></td> </tr> <tr> <td> Password: </td><td> <input type="password" size="13" id="pass_word" name="pass_word" value=""></td> </tr> <tr> <td colspan=2 align="center"><input type="submit" value="Login"> </div></td> </tr> </table> </form> </body> </html>
<?php $Host= '192.168.1.8'; $Dbname= 'john'; $User= 'john'; $Password= 'xxx'; $Schema = 'test'; $Conection_string="host=$Host dbname=$Dbname user=$User password=$Password"; /* Connect with database asking for a new connection*/ $Connect=pg_connect($Conection_string,$PGSQL_CONNECT_FORCE_NEW); /* Error checking the connection string */ if (!$Connect) { echo "Database Connection Failure"; exit; } $query="SELECT * from $Schema.users where user_name='".$_POST['user_name']."' and password='".$_POST['pass_word']."';"; $result=pg_query($Connect,$query); $rows = pg_num_rows($result); if ($rows) { echo "Login Success"; } else { echo "Login Failed"; } ?>
' or 1=1;--
SELECT * from test.members where user_name='' or 1=1;--' and password='';
select * from test.members where user_name='' or 1=1;
';drop table test.lop;--
- Stored the password as md5 in the database
- First select the username,password from the database based on the username provided.
- Then md5 the password given by the user, and compare it with the password got from database.
- If both are matched, then login is success.
$query="SELECT user_name,password from $Schema.members where user_name='".$_POST['user_name']."';"; $result=pg_query($Connect,$query); $row=pg_fetch_array($result,NULL,PGSQL_ASSOC); # Find the md5 for the user supplied password. $user_pass = md5($_POST['pass_word']); if(strcmp($user_pass,$row['password'])!=0) { echo "Login Failed\n"; } else { echo "Login Success\n"; }
' UNION ALL SELECT 'laksh','202cb962ac59075b964b07152d234b70
SELECT user_name,password from test.members where user_name='' UNION ALL SELECT 'laksh','202cb962ac59075b964b07152d234b70';
- Strict type checking ( Don’t trust what the user enters )
- If you expect user name to be entered, then validate whether it contains only alpha numerals.
- Escape or filter the special characters and user inputs.
- Use prepared statements to execute the queries.
- Don’t allow multiple queries to be executed on a single statement.
- Don’t leak the database information to the end user by displaying the “syntax errors”, etc.