我被要求用Flawfinder:分析一些C代码
char * buffer;
size_t len;
// my_fd is a file descriptor
read(my_fd, &len, sizeof(len));
buffer = malloc(len + 1);
read(my_fd, buffer, len);
buffer[len] = ' ';
我在2上收到以下警告:
test.c:xx: [1] (buffer) read:
Check buffer boundaries if used in a loop including recursive loops
(CWE-120, CWE-20).
test.c:xx: [1] (buffer) read:
Check buffer boundaries if used in a loop including recursive loops
(CWE-120, CWE-20).
我试着按照这个答案,修改函数如下:
char * buffer;
size_t len;
// my_fd is a file descriptor
ssize_t ret = read(my_fd, &len, sizeof(len));
if (ret == -1 || ret != sizeof len) {
buffer = NULL;
} else {
buffer = malloc(len + 1);
ret = read(my_fd, buffer, len);
buffer[ret] = ' ';
}
free(buffer);
但漏洞仍然存在。我错过了什么?
更新#1:
我根据@4386427的建议更新了功能,检查了read()
和malloc()
:
char * buffer = NULL;
size_t len;
ssize_t ret = read(my_fd, &len, sizeof(len));
if (ret == sizeof len)
{
buffer = malloc(len + 1);
if (buffer != NULL)
{
ret = read(my_fd, buffer, len);
if (ret == len)
{
buffer[ret] = ' ';
}
free(buffer);
}
}
但一切都没有改变,我该如何进一步提高安全性?
更新#2
因为Flawfinder只做模式检查,而且似乎没有更多的改进可以应用;在这一点上,我将这些错误标记为假阳性。
在上一个代码片段中,我看到有两个地方的返回值处理不正确。1( 你不检查malloc
2(你不检查读取的
尝试:
char * buffer;
size_t len;
// my_fd is a file descriptor
ssize_t ret = read(my_fd, &len, sizeof(len));
if (ret != sizeof len) {
buffer = NULL;
} else {
buffer = malloc(len + 1);
if (buffer != NULL) // Check that malloc was ok
{
ret = read(my_fd, buffer, len);
if (ret == -1) // Check that read was ok
{
// error handling....
//
// for now just do:
ret = 0;
}
else if (ret != len)
{
// Didn't get as much data as expected
//
// Add some error handling....
}
buffer[ret] = ' ';
}
}
free(buffer);