ABV.UNICODE.BOUND_MAP

Buffer overflow-array index out of bounds in mapping function

ABV.UNICODE.BOUND_MAP checks for buffer overrun conditions caused in MultiByteToWideChar and WideCharToMultiByte mapping functions. Typically, the checker detects a condition when WideCharToMultiByte checks buffer boundaries incorrectly and the buffer overflows.

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. It's particularly easy to cause a buffer overflow with MultiByteToWideChar because the size of the input buffer is the number of bytes in the string, and the size of the output buffer is the number of characters. (The opposite is true in the WideCharToMultiByte function.) To avoid this potential condition, it's important to specify a buffer size that is appropriate for the data type the buffer receives.

Vulnerable code example

Copy
  #include "stdafx.h"
  #include <string.h>
  #include <iostream>
  
  using namespace std;
  
  void convert(WCHAR *wcsPath)
  {
      char cpszPath[5] ="";
      WideCharToMultiByte(CP_ACP, 0, wcsPath, -1, cpszPath, 260, 0, 0);
      cout << cpszPath << endl;
  }

                                                

Klocwork produces a buffer overflow report for line 10, indicating that function WideCharToMultiByte may incorrectly check buffer boundaries and overflow buffer 'cpszPath' with size (260). In this case, the function WideCharToMultiByte causes a buffer overflow through a lack of validation of the input buffer size.

Fixed code example

Copy
  #include "stdafx.h"
  #include <string.h>
  #include <iostream>
  
  using namespace std;
  
  
  void convert(WCHAR sText[100]) {
      char szTemp[20];
      int nSize = WideCharToMultiByte(CP_ACP, WC_COMPOSITECHECK, sText, -1, szTemp, 0, 0, 0);
      if (nSize > sizeof(szTemp)) 
      {
          return;
      }else
      { 
          WideCharToMultiByte(CP_ACP, WC_COMPOSITECHECK, sText, -1, szTemp, nSize , 0, 0); 
      }
      cout << szTemp << endl;
  }

                                                

When the size of the target buffer is zero in the fixed example, the function returns the number of bytes needed for the conversion. The input character size is compared to the size of the buffer before the conversion.

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.