Wide characters may can frequently contain null bytes if taken from the ASCII character set. As a result, using narrow-char functions which rely on null-byte termination may can lead to obtuse behavior. Likewise, a narrow-char string which is properly null-terminated may might not be considered so in a wide-char function. Improper use of narrow and wide character strings could result in buffer overflows.
...
The below example uses strncpy, which will copy, at most, 10 bytes in this example, but will stop copying after it encounters a null-byte. Since Because wide-characters may can contain null-bytes, it may the code can stop copying prematurely. It is important to recognize that many narrow-string functions are byte functions , and, thus, may can terminate prematurely.
| Code Block | ||
|---|---|---|
| ||
wchar_t *wide_str1 = L"0123456789"; wchar_t *wide_str2 = L"0000000000"; strncpy(wide_str2, wide_str1, 10); |
...
It should be noted that wcsncpy does not perform null-termination if the source string contains more wide-characters than the destination. As a result, it is possible for an attacker to exploit such a vulnerability by passing a maliciously crafted string to wcsncpy. If the code is intended to copy a certain number of bytes, it may can overflow the buffer by writing multiple bytes as wcsncpy measures copying by wide-characters, not by bytes.
...
Modern compilers recognize the difference between a char* and a wchar_t* pointer. As a result, compiling code that violates this rule will generate warnings. It is feasible to have automated software that recognizes improper-width functions and replaces them with their proper width functions (i.e.that is, using wcsncpy when it recognizes that the parameters are of type wchar_t*).
...
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
Bibliography
Related Guidelines
\[[ISO/IEC 9899:1999|AA. Bibliography#ISO/IEC 9899-1999]\] Section 7.21.2.4, "The {{Wiki Markup strncpy}} function"
\[[
ISO/IEC 9899:1999|AA. Bibliography#ISO/IEC 9899-1999]\] Section 7.24.4.2.2, "The {{wcsncpy}} function"
Bibliography
...
STR37-C. Arguments to character handling functions must be representable as an unsigned char 07. Characters and Strings (STR) 08. Memory Management (MEM)