Wide characters may 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 lead to obtuse behavior. Likewise, a narrow-char string which is properly null-terminated may not be considered so in a wide-char function. Improper use of narrow and wide character strings could result in buffer overflows.
Noncompliant Code Example (Using strncpy instead of wcsncpy)
wchar_t *wide_str1 = L"0123456789"; wchar_t *wide_str2 = L"0000000000"; strncpy(wide_str2, wide_str1, 10);
The above example uses strncpy
which will copy at most 10 bytes in this example, but will stop copying after it encounters a null-byte. Since wide-characters may contain null-bytes, it may stop copying prematurely. It is important to recognize that many narrow-string functions are byte functions, and thus may terminate prematurely.
Noncompliant Code Example (Using wcsncpy instead of strncpy)
char *narrow_str1 = "0123456789"; char *narrow_str2 = "0000000000"; wcsncpy(narrow_str2, narrow_str1, 10);
The above example uses wcsncpy
, which will copy 10 wide-length characters. In most implementations, wide-characters span multiple narrow-characters. The wcsncpy
function will copy at most 10 wide-characters, which is longer than narrow_str1
. As a result, it will write the first 10 bytes of narrow_str1
into narrow_str2
and then continue padding with L'\0'
null wide-characters until 10 wide-characters have been written.
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 overflow the buffer by writing multiple bytes as wcsncpy
measures copying by wide-characters, not by bytes.
Compliant Solution
wchar_t *wide_str1 = L"0123456789"; wchar_t *wide_str2 = L"0000000000"; wcsncpy(wide_str2, wide_str1, 10); /* Use of proper-width function */ char *narrow_str1 = "0123456789"; char *narrow_str2 = "0000000000"; strncpy(narrow_str2, narrow_str1, 10); /* Use of proper-width function */
Risk Assessment
Failure to use the proper-width string functions can lead to buffer overflows and the execution of arbitrary code by an attacker.
Rule |
Severity |
Likelihood |
Remediation Cost |
Priority |
Level |
---|---|---|---|---|---|
STR38-C |
high |
likely |
medium |
P18 |
L1 |
Automated Detection
When compiled with the -Wall
flag, this vulnerability is noticed by gcc
. Many other compilers recognize the improper usage. In addition, tools such as Splint may alert the user.
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
References
[[Linux 07]] Section 3, "strncpy
"
[[Linux 07]] Section 3, "wcsncpy
"