November 04, 2002

Programming Tip

Well, didn't get to spend much time on the book after I left the computer. I thought my daughter was going out to play with her friends, but that didn't end up happening. So we spent the day together.

The book has reminded me of a lot of fundamental programming techniques that are lost in the school system. My favorite is brain dead easy stuff that we all do, and we shouldn't. The easiest one I can think of is about "failing securely". This is the addage where in case of fault you should fail to a secure state, and not vice-versa. Let me give you an example.

int ret = isAllowedAccess( ... );

if( ret == ERROR_ACCESS_DENIED ) {
// Error message here... tell the user
}
else {
// OK, do something since you are allowed access
}

If you closely examine that psuedo code, it looks ok. On the surface, the code works flawlessly because if will either alert them if they are not allowed access, or process it if they are. Looks good right? Wrong. When coding we need to expect that we are in a hostile environment and it may fail. Code that doesn't fail well can cause lots of problems. Look at the above example. What would happen if during the call to isAllowedAccess it returned ERROR_NOT_ENOUGH_MEMORY? Whoops. You just authenticated someone incorrectly. We all have done this. And we need to remind ourselves that is not the way to handle it. The better way would be to fail well. Something like this:

int ret = isAllowedAccess( ... );

if( ret == SUCCESS ) {
// Ok, do something since you are allowed access
}
else {
// Error message here. Could be ANYTHING. Tell the user
}

Now, I could make it more programmer safe if I switched the if statement around a bit to:


if( SUCCESS == ret )

But this is an issue to cover when discussing coding style. Why would I write it that way? Well, if I accidentally forgot a single equal sign, I would be setting ret to a SUCCESS status which may again give access when it shouldn't. Further to this... if the variable is used later on, it will be in the wrong state. In the end, many developers are ok with putting the var first, and that is ok to as long as you are careful.

Anyways, that ends my "Writing Secure Code" tutorial for the day. I need to get going to work. I am going to go check my work and make sure some of my own code fails securely. TTYL

Posted by SilverStr at November 4, 2002 05:14 PM