如何解决强化报告中的整数溢出? (C代码)

时间:2018-10-26 03:58:34

标签: c fortify

当我分配一个缓冲区(通过读取头的缓冲区大小)时,我具有有关图像功能的功能。 强化报告在这里告诉我“整数溢出”。 但是,无论是我修复代码还是检查颜色值, 强化报告仍然告诉我“整数溢出”

有人有什么建议吗?

代码:

int ReadInt()
{
    int rnt=0;
    rnt = getc(xxx);
    rnt +=  (getc(xxx)<<8);
    rnt += (getc(xxx)<<16);
    rnt += (getc(xxx)<<24);
    return rnt;
}

int image()
{
....
        image->header_size=ReadInt();
        image->width=ReadInt();
        image->height=ReadInt();
....    
        image->colors =ReadInt();

        int unit_size = 0;
        unit_size = sizeof(unsigned int);
        unsigned int malloc_size = 0;
        if (image->colors > 0 &&
            image->colors < (1024 * 1024 * 128) &&
            unit_size > 0 &&
            unit_size <= 8)
        {

            malloc_size = (image->colors  * unit_size);
            image->palette = (unsigned int *)malloc( malloc_size );
        }

....
        return 0;
}

堡垒报告:

Abstract: The function image() in xzy.cpp does not account for
integer overflow, which can result in a logic error or a buffer overflow.
Source:  _IO_getc()
59 rnt += (getc(xxx)<<8);
60 rnt += (getc(xxx)<<16);
61 rnt += (getc(xxx)<<24);
62 return rnt;

Sink: malloc()
242 malloc_size = (image->colors * unit_size);
243 image->palette = (unsigned int *)malloc( malloc_size );
244

1 个答案:

答案 0 :(得分:0)

每次将“ 1”位移入符号位时,向左移int就有可能发生不确定的行为(UB)。

int中使用任意some_int << 8值都可能发生这种情况。

getc()返回unsigned char范围内的值或负EOF。向左移动EOF是UB。用128 << 24向左移动128之类的值就是UB。

相反,使用 unsigned 数学从getc()累积非负值。

建议更改功能签名以适应文件结尾/输入错误。

#include <stdbool.h>
#include <limits.h>

// return true on success
bool ReadInt(int *dest) {
  unsigned urnt = 0;
  for (unsigned shift = 0; shift < sizeof urnt * CHAR_BIT; shift += CHAR_BIT) {
    int ch = getc(xxx);
    if (ch == EOF) {
      return false;
    }
    urnt |= ((unsigned) ch) << shift;
  } 
  *dest = (int) urnt;
  return true;
}

(int) urnt转换调用“实现定义的信号或实现定义的信号被发出”,这通常是预期的功能:urnt上方INT_MAX中的值“环绕”。

或者,学步代码可以使用:

  if (urnt > INT_MAX) {
    *dest = (int) urnt;
  } else {
    *dest = ((int) (urnt - INT_MAX - 1)) - INT_MAX - 1;
  }

image->colors * unit_size的改进。

    //int unit_size = 0;
    // unit_size = sizeof(unsigned int);
    size_t unit_size = sizeof(unsigned int);
    // unsigned int malloc_size = 0;
    if (image->colors > 0 &&
        // image->colors < (1024 * 1024 * 128) &&
        image->colors < ((size_t)1024 * 1024 * 128) &&
        unit_size > 0 &&
        unit_size <= 8)
    {
        size_t malloc_size = (size_t) image->colors * unit_size;
        // image->palette = (unsigned int *)malloc( malloc_size );
        image->palette = malloc(malloc_size);

1024 * 1024 * 128INT_MAX < 134217728(28位int)时的问题。
参见There are reasons not to use 1000 * 1000 * 1000