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

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

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

    1  #include "stdafx.h"
    2  #include <string.h>
    3  #include <iostream>
    5  using namespace std;
    8  void convert(WCHAR sText[100]) {
    9      char szTemp[20];
   10      int nSize = WideCharToMultiByte(CP_ACP, WC_COMPOSITECHECK, sText, -1, szTemp, 0, 0, 0);
   11      if (nSize > sizeof(szTemp)) 
   12      {
   13          return;
   14      }else
   15      { 
   16          WideCharToMultiByte(CP_ACP, WC_COMPOSITECHECK, sText, -1, szTemp, nSize , 0, 0); 
   17      }
   18      cout << szTemp << endl;
   19  }

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.


This checker can be extended through the Klocwork knowledge base. See Tuning C/C++ analysis for more information.