Securing If Statements

Posted by on January 30, 2010

While recently reviewing the details of the GSSP-.NET certification, I came across the topic of “securely formed if and while statements.”  At first, I was a little confused about what this really meant.  I believe that a securely formed ‘if’ statement would be one that has the constant on the left, rather than the right.  I have seen this many times in some code examples, but have never understood the reason for it.  I think this was more of an issue for more seasoned programmers coming from languages that thrived well before .NET came along.  Here is an example of this issue:

if ( myObject == null)    // Less Secure *

if ( null == myObject)   // More Secure

In the example above, they are both valid if statements.   *They would become insecure when the developer forgets the double equal sign (==) and instead just uses a single equals (=) sign.  This would not compare, it would assign, and that could cause a vulnerability.  In the second if statement, if the developer tried to assign to a constant, an error would be thrown.  If they tried to assign to a different variable, possibly no error, and the expected data could be modified. 

Fortunately, .NET’s compiler will warn you if you do this. This would appear to make this topic sort of moot for a .NET security exam.  This is how I felt too, until I came across this mistake in some Javascript code.  Javascript doesn’t have a compiler, so it might be possible to miss this if the code is not tested completely.  .Net developers spend a lot of time with Javascript, and may work with other languages, so it is important to understand these subtle differences when writing code. 


Comments are closed.