MySQL Injection Attacks

As a PHP developer, I work quite a bit with MySQL database tables, both in the course of developing new websites / web applications, as well as modifying or adding features to existing websites.
One thing that always surprises me when working on code written by others is how frequently the code is subject to what is called MySQL Injection Attacks.
MySQL Injection Attacks are basically where, due to poorly written code, hackers can execute custom MySQL commands (that the developer did not wish the script to be able to execute). These hacks can range from deleting all data in a database table, to logging in as a user, to even stealing data from databases in certain cases.
Well-written MySQL queries can easily prevent such attacks. However, many developers, either out of ignorance or, well, laziness, just don’t properly write their queries.
Let’s back up a few steps here. Some servers, especially in past years, have had a PHP option called Magic Quotes (deprecated as of PHP 5.3.0) enabled. This option automatically “escapes” special characters in data that users submit, say, through a web form.
This escaping is necessary on all user-submitted data that is used in a MySQL query. However, setting the server to automatically escape all user-submitted data is problematic for several reason.
A much better way of doing it is to escape each piece of user-submitted data right when it is inserted into the query. Most MVC frameworks which contain some database model have their own custom-named function that can do this for you.
For those of you who are writing in raw PHP code, PHP has a built-in mysql_real_escape_string function, which you can use to obtain the same results (many custom database libraries use that function).
Anyway, there is no excuse for programmers to not take this small, basic step in securing their web applications, so make sure you take advantage of the tools at your disposal here.

2 thoughts on “MySQL Injection Attacks

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s