Sterilize Your Inputs, Protect Against SQL Injection

I write this not with the intent of telling people how to hack, but with the hopes that people will realize how easy it is to protect against.

How to Hack Poorly Coded Forms

The basic idea in SQL injection is that the app puts together a database query based on the input you’ve entered. If you enter the right input, and the app doesn’t check for it, you can control the database. The “skeleton key” is the most common SQL injection attack. Typically, an app checks login creds like so:

But, what if we enter the username:

That gives us the query:

Since the hyphens comment out the password check, and we added or 1=1, it will return every row. The app will then grab the first row, expecting only one row to be returned. Typically, this will be the first row, and typically the first row is an admin user. By inputting a specific username and no password at all, we’ve gained admin access to the app.

Also, depending on the database type, you may also be able to use the same method to run a query such as:

So, a random person that didn’t even log in just truncated your database. Sucks to be you.

How to Fix It

The fix is VERY simple. Any time you have user-inputted text (including http headers, we don’t trust them AT ALL) you need to escape certain characters. If you’re a PHP developer, just use the function mysql_real_escape_string and the problem is solved. If you’re not a PHP developer, or want to understand more about how it works, you need to prepend backslashes to the following characters: \x00, \n, \r, , ‘, “, and \x1A

That’s it. You’re app is safe from instant admin access, random losses of all data, and a ton of other nasty stuff people may do to you.