Wednesday, September 24, 2008

Does strong typing produce more secure code?

The OWASP AppSec Conference 2008 is underway in New York this week. I attended a number of interesting presentations including Hans Zaunere's which addressed PHP's unwarranted notoriety for being insecure. It seems there were some people in the audience were not convinced because someone suggested that PHP's lack of strong typing was somehow a liability.

Apparently this person had performed code audits and discovered SQL injections where the programmer constructed an SQL statement without escaping a field because they assumed the user supplied parameter would always be an integer.

For example:
$age = $_GET['age'];
$sql = "INSERT INTO employee (age) VALUES ($age)";
Of course the supplied 'age' parameter could be a string like:
42); DROP TABLE employee ....
and thus you have the potential for SQL injection.

So does it make sense to blame PHP's lack of strong typing for SQL injections?

No. This case is no different in Java:
String age = request.getParemeter("age");
String sql = "INSERT INTO employee (age) VALUES (" + age + ")";
In both languages we need to either cast and validate the value or better still always escape everything int or otherwise. Escaping SQL parameters (e.g. with mysql_real_escape_string) ensures that the code is not vulnerable to SQL injection. Validation should be used to prevent putting garbage into your database.

The bottom line is that you must escape all parameters when constructing an SQL statement. This is true regardless of what programming language you use.

Strong typing is a constraint used to help the compiler find mistakes and optimise the resulting machine code. But for programmers who know the language well (which is usually a prerequisite for any real project), strong typing mostly equates to more typing.