Monday, June 20, 2011

mysql - sql injection prevention

If you have ever taken raw user input and inserted it into a MySQL database there's a chance that you have left yourself wide open for a security issue known as SQL Injection.


SQL injection is someone inserting a SQL 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.


for PHP users, All you need to do is use the function mysql_real_escape_string.


echo "Escaped Evil Injection:";
$name_evil = "'; DELETE FROM customers WHERE 1 or username = '"; 
$name_evil = mysql_real_escape_string($name_evil);
$query_evil = "SELECT * FROM customers WHERE username = '$name_evil'";


Result
Escaped Bad Injection:
SELECT * FROM customers WHERE username = '\'; DELETE FROM customers WHERE 1 or username = \''


SQL Hacks      SQL Injection Attacks and Defense     Web Security Testing Cookbook: Systematic Techniques to Find Problems Fast