Saturday, July 26, 2008

C++ Hard To Do Security Right Easy To Do Wrong

Whenever possible you should make it easy to do the right thing and hard to do the wrong thing.

From a security point of view C++ may be broken simply because this dynamic is not only missing but reversed.

Take the function "strcpy". It is part of the standard library because C++ lacks a string class and thus it is commonly used. This function comes to mind because I added a huge chunk of existing code to my project. The code base liberally used "strcpy". Now in the "hard to do wrong" fashion the compiler warned on dozens of these and other security obsolete functions.

The security based warnings indicated in good "easy to do right" fashion that one should use "strncpy". The problem is that it often hard to determine the size of string at compile time, which the "n" in "strncpy" requires.

So you can see my dilemma either I retrofit size checking code in all of this imported code or live with the numerous security warnings and the reality they represent in terms of security holes.

Two recommendations from the community raised more concerns than comfort. One was to disable the warning. One poster included the amusing joke that starts with "Doctor it hurts when I do this.." Another disturbing recommendation was to replace the function call to "strcpy" with a hand coded replacement that had the same Stack Overflow problem.

So the effect was the practitioners in this space did not do right and in fact did wrong. Why? Because the language C++ makes it easy to do wrong. In this case the direct memory access. This is because it is hard to do right due to the lack of a standard string class that manages the memory access.

No comments: