View Single Post
11-19-2010, 09:35 AM   #1
Jeff
Administrator
 
Jeff's Avatar
 
Join Date: Jul 2010
Posts: 402
Rep Power: 10
Jeff is getting browny points
Protecting Against MySQL Injections

I just had the not so fun task of auditing some PHP code that had a lot of vulnerabilities. These were all MySQL injection type attacks. I had found them mostly because of the MySQL errors they generated in our logs. If you are writing PHP scripts and you are using MySQL you must sanitize your data! Never assume nobody will know. It is easy to find.

Here is an example, this script will look up widgets of certain category ID:

http://www.somesite.com/somePHPscript.php?viewCategory=19

Well, a BAD way to do this:

Code:
"SELECT * FROM widgets WHERE category_id = " . $_REQUEST['viewCategory'];
What's wrong with that? Well, what if I call the URL like so:

Code:
http://www.somesite.com/somePHPscript.php?viewCategory=19%20union%20truncate%20widgets
Now that query would be:

Code:
SELECT * FROM widgets WHERE category_id = 19 union truncate widgets;
Your widgets tables my dear friend, is history.

How would you combat that? Here you go:

Code:
"SELECT * FROM widgets WHERE category_id = " . intval($_REQUEST['viewCategory']);
intval() converts whatever is passed to it to an integer. So regardless of what is "injected" into $_REQUEST['viewCategory'] it will be converted to an integer.

What if you are using text? Example:

Code:
"UPDATE users set name='$username'"
The mysql_real_escape_string() function will make that variable safe:

Code:
"UPDATE users set name='" . mysql_real_escape_string($username) . "'"
These two simple techniques will take care of 99% of injection attempts!
Jeff is offline   Reply With Quote