Sunday, August 22, 2010

MySQL Injection for Beginners - Part 1/2

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.
SQL injection is a code injection 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 an instance of a more general class of vulnerabilities that can occur whenever one programming or scripting language is embedded inside another. SQL injection attacks are also known as SQL insertion attacks.

The situation is that we have to validate users by their username , and you have PHP code to handle the login as shown below, we will look at difference input and the resulting queries.
$username = $_POST['username']
$query = "SELECT * FROM users WHERE username = '$username'" ;
Normal Users: Username: eferuzi This will result to the $query of 
SELECT * FROM users WHERE username = 'eferuzi' AND password='mypassword'
Injection Users: Username: or 1  This will result to the $query of 
SELECT * FROM users WHERE username = '' or 1=1
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,  and OR clause of 1 will always be true and so every single entry in the "users" table would be selected by this statement!
The above example displayed a situation where an attacker could possibly get access to a lot of information they shouldn't have, the attacks can be a lot worse. For example an attacker could empty out a table by executing a DROP statement.

Injection Users: Username: '; DROP TABLE users;  This will result to the $query of 
SELECT * FROM users WHERE username = ''; DROP TABLE users;
The effect of last example can be only be imagined.

Next: MySQL Injection for Beginners Part 2/2- Preventing SQL injection

No comments:

Post a Comment