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

Copy
  #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

Copy
  #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.

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.