SQL injection & the Kaspersky hack
Last week I read an article on webwereld titled ‘2008 was year of the SQL injection attack‘. It was based on an article with the same title on networkworld.com. Apparently SQL injection has taken over the lead from XSS. Not surprisingly the first user-comment stated that almost 100% of the exploits were certainly in PHP applications written by would-be programmers. With things so obvious it’s of course unneccessary to provide factual data backing up such a statement. So, nothing to win in that discussion. Three days ago news came that a customer database of Kaspersky was hacked. By using SQL injection. On a PHP website. Could commenter X be right?
It is true that PHP allows novice as well as experienced programmers to achieve ‘what they want’. And the novice might adopt some very bad practices. But does that make PHP an insecure programming language? Compare it to driving a car. Yes, you can drive around like a maniac and wreak havoc on the unaware. But does that make a car an unsecure vehicle? The PHP platform offers enough techniques to rule out SQL injection attacks:
-
Prepared statements. There’s no need to concat potentially harmful data in SQL statements. Provide them as a parameter when executung a prepared statement. More efficient too.
-
ORM. If you think SQL should be behind an abstraction layer, you can do so. Propel and Doctrine are the best known solutions for PHP.
-
Well structured programming. If, for some reason, you want to build queries the old way you can force upon yourself (or your team) some good practices. See example below.
$dataTainted[‘un’] = $_POST[‘un’]; $dataTainted[‘pw’] = $_POST[‘pw’];
// escape all array values using a custom function of some sort $dataSafe = mysqlEscapeValues($dataTainted);
$query = <<<SQL SELECT * FROM users WHERE un = “{$dataSafe[‘un’]}” AND pw = SHA1("{$dataSafe[‘pw’]}") SQL;
And that’s just the coding part of the story. In the area of application design a lot can be done to minimize the consequences of an exploit. For example, different database users can be set up that have different levels of access. Only parts of a website needing customer data then use the credentials that do provide such access.
So, for PHP there are good practices and solutions aplenty. For more information on SQL injection one can start at OWASP or Wikipedia. And finally, the subject isn’t non-existent in .NET and JSP.