A hands-on example for SQL injection using PHP and MySQL
It also offers an overview how it gets into in our applications and how we can overcome SQL Injection.
2. What is SQL Injection?
• SQL injection is a code injection technique, used to attack
data-driven applications, in which nefarious SQL
statements are inserted into an entry field for execution
(e.g. to dump the database contents to the attacker).
• SQL injection must exploit a security vulnerability in an
application's software, for example, 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.
3. Causes of SQL Injection
• Incorrectly filtered escape characters
Attacker sends following input in a text field and developer doesn’t filters it for
further computation.
myuser' or 'foo' = 'foo' --
• Incorrect type handling or passing wrong data to DB
Developer sends this unfiltered data to database.
<?php
$sql = "SELECT *
FROM users
WHERE username = 'myuser' or 'foo' = 'foo' --
AND password = 'a029d0df84eb5549c641e04a9ef389e5'";
?>
5. SQL Injection Example
PHP File – [injection.php]
<?php
//connection to the database and select a DB to work with
$dbhandle = mysql_connect('localhost', 'root', '') or die('MySQL not connected');
mysql_select_db('php_security',$dbhandle) or die ( 'Could not select php_security' );
// execute the SQL query and return records
$username = $_POST["username"];
$password = $_POST["password"];
//uncomment these to fix SQL injection
//$username = mysql_real_escape_string( $_POST["username"] );
//$password = mysql_real_escape_string( $_POST["password"] );
$query = "SELECT * FROM users WHERE username='$username' AND password='$password'";
$result = mysql_query( $query , $dbhandle);
// fetch tha data from the database
$num = mysql_num_rows($result);
if ($num > 0) {
print 'got a matching user';
}
// close the connection
mysql_close ( $dbhandle );
6. What’s wrong with the code
//execute the SQL query and return records
$username = $_POST[‘username’];
$password = $_POST[‘password’];
$query = "SELECT * FROM users WHERE username = $username AND
password=$password";
In the above example, if we take $password as
myuser' or 'foo' = 'foo
$query becomes =
SELECT *
FROM users
WHERE username = ‘prady’
AND password = 'myuser' or 'foo' = 'foo'
7. Fixing the code
//execute the SQL query and return records
$username = mysql_real_escape_string( $_POST[‘username’] );
$password = mysql_real_escape_string( $_POST[‘password’] );
$query = "SELECT * FROM users WHERE username = $username
AND password=$password";
8. Complete code
A copy of complete code is available here
https://github.com/prady00/php-security-essentials