SQL Injection wows
I recently picked up “Programing PHP 2nd ed” and I was dismayed to see the DB chapter. Don’t get me wrong any programing book that does not cover DBs is not complete. My problem is that it discusses runing SQL strings and it mentions placeholders in passing, and preparing statements as performance feature. Given today’s web environment and the multitude of sites that suffer from SQL Injection attackts most of them being scripting (asp,php,ect..) they should it make a point when mentioning placeholders, that, whenever user input is being passed to the DB place holders should be used.
I’ve interviewed many developers that can not tell me what the advantage is for using place holders other than in prepared statements for performance reasons. The most important reason to use place holders is to prevent malicious user inputs from corrupting your sql.
Take for instance a user login function might do something like this:
$rs = $db->query("select * from users where user_name = '" + $user + "'");
Instead of
$rs = $db->query("select * from users where user_name = ?", array($user));
the difference in this two pieces of code is that if I pass “x’;delete * from users; select * from user_name where user_name = ‘x” to your login function the first code would execute the whole string as 3 different sqls effectively wiping out your users table. Meanwhile the second approach will return no rows unless there is a user with that as a user name.
There are countless posts about escaping/scrubbing user input prior to using it in DB scripts and most of them fail b/c there are too many ways to get around it. The sad part is that by using prepared statements or atleast placeholders the DB will do the right thing every time. This should have never been an exploit in the first place. ALL intro books to DBs in any language should point this out.
SQL injection is in the no 2 security vulnerabilities for web applications. It costs millions of dollars every year and it is absolutely unessesary. Whith a little education of the programing masses SQL Injection attacks would be a thing of the past. Then we can concentrate on XSS and why we need to escape user input on the way out as well
I’m picking on PHP, but I’ve interviewed many (actually most) java developers (with 8+ years of expericence) who tell me that you use prepared statements for performance reasons and are shocked to find out about bad user input and SQL injection (the only reason we don’t see more SQL Injection attacts in big java apps is b/c frameworks like hibernate are used and they do the right thing.) This is a very sad statement since those are the same people building our financial infrastructure…. But don’t worry I don’t hire anyone who can’t answer that properly….