Web developers are responsible for writing websites that work today, but also years or even decades from now (though I would argue the average website shouldn’t be left alone for a decade).
It can be difficult to protect a website against all future attacks. There is one big one we all have to be prepared for (because it is just so easy to fix)… SQL Injection attacks.
What is an ‘SQL Injection Attack’?
SQL Injection is exactly what it sounds like, injecting SQL where it doesn’t belong.
URL parameters are frequently used to identify dynamic pages (although not good for SEO) such as:
What’s so dangerous? What about this:
That URL will probably result in a query similar to the following:
SELECT * FROM Pages WHERE id = 107 OR 1
See where it gets dangerous now? That’s not even the beginning of it. Attackers are so adept with this exploit, that they can craft URLs to do all sorts of things — add admin accounts, reset passwords, change pages, erase content, etc.
Another common issue is on login scripts, imaging logging in with the following:
Most users wouldn’t do the following:
sean’ OR 1
Because look at the final SQL string:
SELECT * FROM Users WHERE username = ‘sean’ OR 1
If that protected an admin area, the user has probably just logged in.
How do web developers protect against SQL injection attacks?
The best way is a simple function:
mysql_real_escape_string ( string $str )
Make sure all parameter / user entered input is filtered with that function and you will do fine. Lets take a quick look at how the login would have been affected:
$strSQL = "SELECT * FROM Users WHERE username = '".mysql_real_escape_string($_GET['username'])."'"; mysql_query($strSQL);
Instead if passing in a dangerous SQL string, we end up passing the following:
SELECT * FROM Users WHERE username = ‘sean\’ OR 1′
The result will just be nothing (unless you have some witty users).
Additional levels of validation are helpful. If you are expecting an integer, you can use intval. The more specific you can force your code to be, the better.
No comments yet.