Devshed article about SQL Injection (or why security related articles should only be written by experienced people)

Through PHPDeveloper I came across a Devshed article related to SQL Injection.

The one major flaw in the article is that it is suggested input validation is enough protection. This is not the case. Lets start with this example (literal copy-paste):

<?php

//Validate text input
if (! preg_match('/^[-a-z.-@,'s]*$/i',$_POST['name']))
{
} else
if ($empty==0)
{
}
else
{
}
?>

Ignoring the syntax errors, I believe the author here actually intended to allow the usage of the single quote character ('). This will allow sql injection in a lot of queries.

The worst part is the following:

Want stronger protection? If you need stronger protection you can validate the user input using the above scripts andmysql_real_escape_string; this will offer secondary protection in case the above validation scripts fail due to some reason. Discussing this feature is beyond the scope of this article and you can read useful resources on:http://www.php.net/mysql_real_escape_string

However, before you can use this feature, you must be connected to a MySQL database, or else it will return an error. Some really talented hackers can play around with mysql_real_escape_string, which is why it is highly recommended to have a double filter in your scripts (validating scripts +mysql_real_escape_string) to make hacking much more difficult.

Here it is is suggested that mysql_real_escape_string should be used only in the event somebody feels they need 'more' protection. Also, I would like to meet these talented hackers.

What you really should do

  • Always use mysql_real_escape_string. Escaping and validating serve two (important) purposes, and validating does not take away the need to escape. mysql_real_escape_string escapes many more 'bad' characters and it works with different collations.
  • Blacklisting 'bad' things is in most cases a bad idea. Always try to use whitelists for acceptable input.
  • Don't write security related articles if you don't really know the subject. You are potentially placing people at risk, and you promote bad habits.

Respond