gpt4 book ai didi

c++ - 从文件中读取索引是否存在缓冲区溢出漏洞?

转载 作者:太空狗 更新时间:2023-10-29 21:09:49 24 4
gpt4 key购买 nike

最近使用静态分析工具(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来自外部来源,然后将其提升为 size_t当你调用reservefread .自 size_t是无符号类型,如果您从文件中读取的值是负数,则提升为 size_t 时的结果值将远大于 numVertices 的绝对值在大多数平台上。结果是您将尝试保留和读取大量 vector 。如果这两个操作成功,您将尝试 new负数组大小。你的for如果你走到那一步,循环保证永远不会执行。

解决方法是将值读取为无符号整数,或者更好的是 size_t ,尽管这将要求您更改写入该值的代码。另一种选择是至少验证该值。信任来自外部来源的数据是成为本周漏洞的好方法。

关于c++ - 从文件中读取索引是否存在缓冲区溢出漏洞?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56993391/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com