One of the features that the Whidbey release of Visual C++ is going to bring is the new Secure CRT. The C++ library team has put a lot of work into creating safe alternatives to the old C runtime library functions that seem to always be behind security exploits. Michael Howard gave a quick introduction to this feature in his Code Secure column this month.
The new C functions are named similarly to the functions they’re intended to replace, but they have an _s suffix. For instance, strcpy maps to strcpy_s. Some functions that don’t need signature changes did not get renamed. For instance calloc’s implementation has changed to check against integer overflow attacks, but since this does not affect the method’s signature or performance characteristics, it is still named calloc. Although the changes to the CRT are not yet standardized, Microsoft has submitted them to ANSI, so hopefully in the future programs that take advantage of the new safer functions will be able to be ported to non-Microsoft compilers. (The submission to the standardization committee can be found online at: http://std.dkuug.dk/jtc1/sc22/wg14/www/docs/n1031.pdf)
As an example of the mapping, strcpy went from being defined as:
char *strcpy(char *strDest, const char *strSrc); to
errcode strcpy_s(char *strDest, size_t sDest, const char *strSource);
The new functions do several things, including:
- checking all input parameters
- requiring buffer sizes
- writing null terminators when writing string output
- correctly ACL files
The way that invalid parameters are handled is especially interesting. Instead of simply asserting, and quitting out, the CRT provides an opportunity for you to handle these problems through the _set_invalid_parameter_handler function. You can do whatever you’d like in your invalid parameter handler, however as soon as it returns, the program will be exited.
On the C++ side of things, ATL and MFC have been updated to use the secure functions. An addition being made to the STL is the concept of checked iterators. These are iterators that won’t let you walk off the end of a STL structure. In the event that an error is detected by the C++ library, there are two possible behaviors. Setting _SECURE_SCL_THROWS to 0 (the default), the invalid parameter function will be called. However, setting this macro to 1 will cause an exception to be thrown.
By default compiling a C/C++ program in Whidbey will result in warnings when functions need to be changed to their secure counterparts. However, the enhancements made to the STL will not be available by default. Instead, you must define the _SECURE_SCL macro to be equal to 1.
As we get closer to an official Whidbey release, the C++ team will be producing more documentation on these changes, and I’ll post links in this blog.