Wednesday 11 May 2011

MYSQL

MYSQL Injection

SQL injection is yet another common vulnerability that is the result of lax input validation.

example SQL Injection Attack

<?php
 // We didn't check $_POST['password'], it could be anything the user wanted! 
For example: 
$_POST['username'] = 'aidan';
$_POST['password'] = "' OR ''='";
// Query database to check if there are any matching users 

$query "SELECT * FROM users WHERE user='{$_POST['username']}' AND password='{$_POST['password']}'";mysql_query($query);
// This means the query sent to MySQL would be: 

echo $query;
 ?>
The query sent to MySQL: 
SELECT * FROM users WHERE user='aidan' AND password='' OR ''=''
This would allow anyone to log in without a valid password.
 
The correct way to do it to prevent database attack: 
<?php
function check_input($value){

// Stripslashes
if (get_magic_quotes_gpc())  {

  $value = stripslashes($value);
  }
// Quote if not a number
if (!is_numeric($value))
  {
  $value = "'" . mysql_real_escape_string($value) . "'";
  }
return $value;
}

// Make a safe SQL

$user = check_input($_POST['user']);