Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Code Block
bgColor#ffcccc
char *narrow_str1 = "0123456789";
char *narrow_str2 = "0000000000";

wcsncpy(narrow_str2, narrow_str1, 10);

Compliant Solution

The below example uses the appropriate-width function versions. Using wcsncpy for wide-char strings and strncpy for narrow-char strings will ensure that data is not truncated or overwriting extra memory.

Code Block
bgColor#ccccff
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 */

Implementation Details

C99 recognizes wchar_t * and char * as distinct types. As a result, many compilers will yield a warning if the inappropriate function is used. For example, the following warnings were generated when the second non-compliant example was compiled with no flags in GCC on a Linux i686 platform:

...

Since these are just warnings, the compiled code can still be run.  When run on the i686 Linux platform mentioned above, both noncompliant code examples began copying information from out of the bounds of the arguments.  This behavior is indicative a possible buffer overflow vulnerability.

Compliant Solution

The below example uses the appropriate-width function versions. Using wcsncpy for wide-char strings and strncpy for narrow-char strings will ensure that data is not truncated or overwriting extra memory.

Code Block
bgColor#ccccff
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.

...