簡體   English   中英

從文件中讀取索引是否存在緩沖區溢出漏洞?

[英]Is reading an index from a file a buffer overflow vulnerability?

我最近使用靜態分析工具(Checkmarx)來掃描舊游戲引擎的源代碼,以查看其中是否存在任何緩沖區溢出漏洞。 我很驚訝地看到以下代碼被標記為緩沖區溢出的可能來源:

// Get a pointer to a file that describes a 3D model
std::string filename = "my_3D_model.obj"
FILE* stream;
fopen_s(&stream, filename.c_str(), "rb");

// Read the number of vertices that make up the 3D model
int numVertices = 0;
fread(&numVertices, sizeof(int), 1, stream);

// Read the vertices and store them in a vector
// The static analysis tool doesn't complain about the use of numVertices to
// reserve space and to read from the file
std::vector<Vertex> vertices;
vertices.reserve(numVertices);
fread(vertices.data(), sizeof(Vertex), numVertices, stream);

// ...

// Copy the vertices from the vector to an array that has been allocated on the heap
// The static analysis tool complains because numVertices, which was read from a file,
// is being used as an index
Vertex* meshVertices = new Vertex[numVertices];
for (int i = 0; i < numVertices; i++)
{
    meshVertices[i] = vertices[i];
}

靜態分析工具將其稱為“來自輸入緩沖區溢出漏洞的索引”。 它看到int i的范圍從0到numVertices ,它是從文件中讀取的,它認為這可能導致緩沖區溢出。 但在這種特殊情況下它真的可能嗎? numVertices用於分配緩沖區的大小,因此我沒有看到緩沖區溢出是如何發生的。 如果有可能,你會如何防止它? 請注意,我無法更改緩沖區的類型,因為這會破壞太多代碼。

感謝您的任何信息!

警告絕對正確。 您正在從外部源讀取已簽名的int ,然后在調用reservefread時將其提升為size_t 由於size_t是無符號類型,如果從文件中讀取的值是負數,則提升為size_t時的結果值將遠大於大多數平台上numVertices的絕對值。 結果是你將嘗試保留並讀取大量的向量。 如果這兩個操作成功,那么您將嘗試new的負數組大小。 保證你的for循環永遠不會執行,如果你走得那么遠。

修復是將值讀取為unsigned int,或者更好的是size_t ,盡管這將要求您更改寫入值的代碼。 另一種選擇是至少驗證價值。 信任來自外部資源的數據是成為本周漏洞的好方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM