View Single Post
11-19-2010, 09:35 AM   #1
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:

Well, a BAD way to do this:

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

Now that query would be:

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:

"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:

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

"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