1708
int success;
// buffer with size set to maximum size for input to log file
char buf[LOG_INPUT_SIZE];
// copy filename to buffer
strncpy(buf, filename, length);
// save to log file
success = saveToLogFile(buf);
return success;
}
However, in this case the string copy method, strncpy, mistakenly uses the length method
argument to determine the number of characters to copy rather than using the size of the local
character string, buf. This can lead to a buffer overflow if the number of characters contained in
character string pointed to by filename is larger then the number of characters allowed for the local
character string. The string copy method should use the buf character string within a sizeof call to
ensure that only characters up to the size of the buf array are copied to avoid a buffer overflow, as
shown below.
Example Language: C (Good)
...
// copy filename to buffer
strncpy(buf, filename, sizeof(buf)-1);
...
Example 5:
Windows provides the MultiByteToWideChar(), WideCharToMultiByte(), UnicodeToBytes(), and
BytesToUnicode() functions to convert between arbitrary multibyte (usually ANSI) character strings
and Unicode (wide character) strings. The size arguments to these functions are specified in
different units, (one in bytes, the other in characters) making their use prone to error.
In a multibyte character string, each character occupies a varying number of bytes, and therefore
the size of such strings is most easily specified as a total number of bytes. In Unicode, however,
characters are always a fixed size, and string lengths are typically given by the number of
characters they contain. Mistakenly specifying the wrong units in a size argument can lead to a
buffer overflow.
The following function takes a username specified as a multibyte string and a pointer to a structure
for user information and populates the structure with information about the specified user. Since
Windows authentication uses Unicode for usernames, the username argument is first converted
from a multibyte string to a Unicode string.
Example Language: C (Bad)
void getUserInfo(char *username, struct _USER_INFO_2 info){
WCHAR unicodeUser[UNLEN+1];
MultiByteToWideChar(CP_ACP, 0, username, -1, unicodeUser, sizeof(unicodeUser));
NetUserGetInfo(NULL, unicodeUser, 2, (LPBYTE *)&info);
}
This function incorrectly passes the size of unicodeUser in bytes instead of characters. The call
to MultiByteToWideChar() can therefore write up to (UNLEN+1)*sizeof(WCHAR) wide characters,
or (UNLEN+1)*sizeof(WCHAR)*sizeof(WCHAR) bytes, to the unicodeUser array, which has only
(UNLEN+1)*sizeof(WCHAR) bytes allocated.
If the username string contains more than UNLEN characters, the call to MultiByteToWideChar()
will overflow the buffer unicodeUser.
Observed Examples
CWE Version 4.14
CWE-805: Buffer Access with Incorrect Length Value
CWE-805: Buffer Access with Incorrect Length Value