warning C6029: possible buffer overrun in call to <function>: use of unchecked value
這個警告表示正將未核取的大小傳遞至使用緩衝區和大小的函式。尚未驗證某些外部來源的資料讀入以查看其是否小於緩衝區。攻擊者可能會刻意替大小指定大於預期甚多的值,導致緩衝區溢位。
一般而言,每當您自未受信任的外部來源讀取資料時,請務必驗證其有效性。驗證大小以確認其在預期的範圍內通常是適當的。
範例
下列程式碼透過呼叫註釋函式 ReadFile 兩次產生這個警告。在第一次呼叫之後,張貼的 attribute 屬性會將第二個參數值標記為不受信任。因此,在第二個呼叫中傳遞未受信任的值至 ReadFile 會產生如下列程式碼所示的警告:
#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 6029
{
return false;
}
return true;
}
若要更正這個警告,請檢查緩衝區大小,如下列程式碼所示:
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 6029
{
return false;
}
return true;
}