read()-检查缓冲区边界(如果在包括递归循环的循环中使用)

时间:2018-10-27 09:04:35

标签: c io buffer-overflow flawfinder

我有这段代码并与Flawinder一起运行,并且在read()函数上获得了此输出:“如果在包括递归循环的循环中使用,请检查缓冲区边界”

有人可以看到问题吗?

**

#include <stdlib.h>
void func(int fd)
{

char *buf;
size_t len;
read(fd, &len, sizeof(len));

if (len > 1024)
return;
buf = malloc(len+1); 
read(fd, buf, len); 
buf[len] = '\0';
}

**

1 个答案:

答案 0 :(得分:1)

您应该检查read()的返回值,以了解对read()的调用是成功还是失败,或者read()是否被信号中断,然后设置errno。对于例如

ssize_t ret = read(fd, &len, sizeof len);
if( (ret == -1 || ret != sizeof len) {
   /* error handling @TODO */
}

最重要的是这里

ret = read(fd, buf, len); /* read() may read less than len characters */ 

read()返回读取的字节数,因此代替此值

buf[len] = '\0';

使用

buf[ret] = '\0'; /* correct way */

示例代码

void func(int fd) { /* assume fd is a valid file descriptor */
        char *buf = NULL;
        size_t len;
        errno = 0; /* set this to 0 */
        ssize_t ret = read(fd, &len, sizeof len);
        if( (ret == -1 || ret != sizeof len) {
                /* error handling @TODO */
        }
        if (len > 1024) {
                return;
        }
        buf = malloc(len+1); 
        if(buf == NULL) {
                /* error handling @TODO */
        }
        ret = read(fd, buf, len);
        if(ret!=-1) {
                buf[ret] = '\0';
                /* do something with buf and free it once usage is done*/
        }       free(buf); /* free the buf */
        else { /* if read failed */
                free(buf); /* free the buf */
        }
}