Warning C6029

Possible buffer overrun in call to 'function': use of unchecked value

Remarks

This warning indicates that a function that takes a buffer and a size is being passed an unchecked size. The data read-in from some external source hasn't been verified to see whether it's smaller than the buffer size. An attacker might intentionally specify a much larger than expected value for the size, which will lead to a buffer overrun.

Generally, whenever you read data from an untrusted external source, make sure to verify it for validity. It's appropriate to verify the size to make sure it's in the expected range.

Code analysis name: USING_TAINTED_DATA

Example

The following code generates this warning by calling the annotated function ReadFile two times. After the first call, the Post attribute property marks the second parameter value untrusted. Therefore, passing an untrusted value in the second call to ReadFile generates this warning as shown in the following code:


#include "windows.h"

bool f(HANDLE hFile)
{
    char buff[MAX_PATH];

    DWORD cbLen;
    DWORD cbRead;

    // Read the number of byte to read (cbLen).
    if (!ReadFile (hFile, &cbLen, sizeof (cbLen), &cbRead, NULL))
    {
        return false;
    }
    // Read the bytes
    if (!ReadFile (hFile, buff, cbLen, &cbRead, NULL))  // warning C6029
    {
        return false;
    }

    return true;
}

To correct this warning, check the buffer size as shown in the following code:

bool f(HANDLE hFile)
{
    char buff[MAX_PATH];

    DWORD cbLen;
    DWORD cbRead;

    // Read the number of byte to read (cbLen).
    if (!ReadFile (hFile, &cbLen, sizeof (cbLen), &cbRead, NULL))
    {
        return false;
    }
    // Ensure that there's enough space in the buffer to read that many bytes.
    if (cbLen > sizeof(buff))
    {
        return false;
    }
    // Read the bytes
    if (!ReadFile (hFile, buff, cbLen, &cbRead, NULL))  // warning C6029
    {
        return false;
    }

    return true;
}

See also