ABV.UNICODE.NNTS_MAP
Buffer overflow from non null-terminated string in mapping function
ABV.UNICODE.NNTS_MAP checks for buffer overrun conditions caused in MultiByteToWideChar and WideCharToMultiByte mapping functions by non null-terminated strings. Typically, the checker detects the condition when either function doesn't terminate the output string automatically.
For more information on the operation of the MultiByteToWideChar and WideCharToMultiByte mapping functions, see the MSDN website.
Vulnerability and risk
Using these mapping functions incorrectly can compromise the security of an application by causing a buffer overflow. To avoid this potential condition, it's important to null-terminate the output string for the function.
Vulnerable code example
#include <windows.h>
#include <stdio.h>
#include <wchar.h>
#include <string.h>
int main()
{
wchar_t wstrTestNNTS[] = L"0123456789ABCDEF";
char strTestNNTS[16];
int res = WideCharToMultiByte(CP_UTF8, 0, wstrTestNNTS, -1, strTestNNTS, 16, NULL, NULL);
printf("res = %d\n", res);
printf("strTestNNTS = %s\n", strTestNNTS);
return 0;
}
Klocwork produces a NNTS report for function 'WideCharToMultiByte', because this function is not guaranteed to write the null termination character at the end of the string. If the destination buffer is used without checking the return value, the non-null terminated string may overflow.
Fixed code example
#include <windows.h>
#include <stdio.h>
#include <wchar.h>
#include <string.h>
int main()
{
wchar_t wstrTestNNTS[] = L"0123456789ABCDEF";
char strTestNNTS[16];
int res = WideCharToMultiByte(CP_UTF8, 0, wstrTestNNTS, -1, strTestNNTS, 16, NULL, NULL);
if (res == sizeof(strTestNNTS)) {
strTestNNTS[res-1] = NULL;
} else {
strTestNNTS[res] = NULL;
}
printf("res = %d\n", res);
printf("strTestNNTS = %s\n", strTestNNTS);
return 0;
}
In the fixed code example, the return value of the function is checked at lines 11 to 14, and the null termination character is added if it's needed.
Related checkers
External guidance
- CERT ARR00-C: Understand how arrays work
- CERT ARR30-C: Do not form or use out-of-bounds pointers or array subscripts
- CERT ENV01-C: Do not make assumptions about the size of an environment variable
- CWE-119: Improper Restriction of Operations within the Bounds of a Memory Buffer
- CWE-124: Buffer Underwrite ('Buffer Underflow')
- CWE-125: Out-of-bounds Read
- CWE-176: Improper Handling of Unicode Encoding
- CWE-787: Out-of-bounds Write
- CWE-806: Buffer Access Using Size of Source Buffer
- STIG-ID:APP3590.1 Application is vulnerable to buffer overflows
Security training
Application security training materials provided by Secure Code Warrior.
Extension
This checker can be extended through the Klocwork knowledge base. See Tuning C/C++ analysis for more information.