In a blog post Danny Kalev published earlier this year on InformIT, an example was presented demonstrating how one could write valid but insecure code involving
auto_ptr which compiles without any warning, despite other warnings Micorsoft’s recent compilers would’ve issued against standard compliant code. Along with other points he made in the post, Danny suggests Micorsoft doesn’t really care about your code safety. I couldn’t have agreed with him more, and would like to contribute my own analysis (aka. my two cents) in support of Danny’s finding.
Most of us are very well aware of the often-exploited security vulnerability in
strcpy, and Microsoft’s answer to it is
strcpy_s, which is said to be a more secure alternative that takes an additional parameter,
numberOfElementsas they called it:
char *strcpy( char *strDestination, const char *strSource ); errno_t strcpy_s( char *strDestination, size_t numberOfElements, const char *strSource );
But wait, doesn’t
strcpy_s look awfully similar to another standard function?
char *strncpy( char *strDest, const char *strSource, size_t count );
Put aside the subtle differences in types of return value and parameter naming/ordering, and the insignificant behavioral difference (in regard to buffer overruns, which only applies when things start to screw up) when
count is too small. They are effectively the same.
Yes, I get the semantical differentiation Micorsoft has been trying to sell us programmers. But I failed to understand how is
strcpy_s more secure than
Wouldn’t it make more sense if compiler vendors would educate programmers (a.k.a. their customers) the habit of using
strncpy instead of
strcpy, and use
count as the size of the memory buffer
strDest points to, for security reasons. But, no, Microsoft had to tell programmers to embrace their proprietary Security Enhanced CRT functions and hints, in a security note, that we can’t use
strncpy does not check for sufficient space in strDest; it is therefore a potential cause of buffer overruns. Keep in mind that count limits the number of characters copied; it is not a limit on the size of strDest.
If the parameter
count couldn’t buy
strncpy security, I just don’t see how
strcpy_s could have made the cut with