Archive for January, 2008
Massive SQL injection attack
Wednesday, January 9th, 2008In case you didn’t see the news, tens of thousands of web sites were hacked to infect visitors and hijack their PCs. The sites were apparently modified by a script that found SQL injection vulnerabilities in sites and used them to add its own code to, well, pretty much every field on every record in the database, hoping one of those fields would be part of the site’s content.
SQL injection is one of the biggest security problems in the PHP world. But, it doesn’t have to be a problem.
The simplest thing you can do to prevent SQL injection is to sanitize your inputs. If you’re expecting an integer, check that the value is an integer before you plug it into your query. Some people suggest using the addslashes() function on any value you plug into a query, but that still leaves room for improvement. The mysql_real_escape_string() function provides a little better security.
An even better way to thwart SQL injection is through prepared statements. They’re supported by the MDB2 library from the PEAR project, and I’m sure many other libraries support them. A prepared statement query looks something like this:
SELECT * FROM users WHERE username = ?
When you run the query, you give the database library a list of values to match up with the ?s in the prepared statement. The library then passes those values to the database, saying “I want you to find this exact value. Don’t interpret it, just look for this value verbatim.” If someone tries SQL injection against a prepared statement, they’re just going to get 0 results back.
Sure, there’s a performance penalty for doing prepared statements, but the security benefits are well worth the overhead. You don’t want your site to be one of the “tens of thousands” infecting other people’s PCs, now, do you?
Edit: modsecurity.org has the query string used in this attack, and information on how the mod_security Apache module can filter out attacks like this.

