Simple SQL Injection

SQL Injection is a technique used to exploit security holes in a system using SQLs such as MySQL. This kind of security hole usually occurs when a programmer doesn’t filter quotes or other meta-characters properly. The following code is an example of a such a vulnerability.

if(mysql_query("SELECT * FROM member_tables WHERE id = '".$login_id."' and password = '".$password."'")){
[...code for login...]
}

If quotes aren’t stripped from the variables $login_id or $password, a malicious user can inject SQL functions. They could login as the first user, in most cases the administrator, by typing in something like this into either of the two variables:

s' or 1=1 --

The one line can be catastrophic to a website’s security. If the quote isn’t filtered, the script will read the code like this

if(mysql_query("SELECT * FROM member_tables WHERE id = 's' or 1=1 --' and password = '[password]‘)){
[...code for login...]
}

The or statement makes it so even if only one condition matches, it will return a true value and execute the script. Since 1=1 is always true, the script will launch no matter what. The rest of the SQL statements are commented out by the two dashes (–). Is this the end? Nope.. If the security of the site is so weak, some one could easily delete all the members from the database. It’s just like the one above, but you add a bit of code and do a bit of guesswork.

s' or 1=1;DROP TABLE member_table; --

This would render this in the script

if(mysql_query("SELECT * FROM member_tables WHERE id = 's' or 1=1;DROP TABLES member_table; -- --' and password = '[password]‘)){
[...code for login...]
}

That just deletes the table. End, unless you have backup.

As devastating as this can be, it’s also very simple to prevent. You simply escape or remove quotes from a query using a built in function. In the case of PHP, the addslashes() function does the trick. So, the script above should be fixed to

$login_id = addslashes($login_id);
$password = addslashes($password);
if(mysql_query("SELECT * FROM member_tables WHERE id = '".$login_id."' and password = '".$password."'")){
[...code for login...]
}

This function adds backslashes (\) before metacharacters which lets the character be treated as just a string and not a special one that affects the acting of the query.

April 27, 2009 in Security, The Internet
Tagged , , ,

Leave a Reply

Using Gravatars in the comments - get your own and be recognized!

XHTML: These are some of the tags you can use: <a href=""> <b> <blockquote> <code> <em> <i> <strike> <strong>