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

how to solve Integer Overflow in fortify report? (C code)

我有一个关于图像特征的函数,当我 malloc 一个缓冲区时(缓冲区大小通过读取头)。 强化报告在这里告诉我 "Integer Overflow"。 但是,无论我是修复代码还是检查颜色值, 强化报告仍然告诉我"Integer Overflow"

有人有什么建议吗?

代码:

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

左移 int 有可能 未定义的行为 (UB) 任何时候 "one" 位被移入符号位。

这可能发生在任意 int 值上,如 some_int << 8

getc() return unsigned char 范围内的值或负值 EOF。左移一个 EOF 是 UB。使用 128 << 24 向左移动 128 之类的值是 UB。

而是使用 unsigned 数学从 getc() 累加非负值。

建议更改函数签名以适应 end-of-file/input 错误。

#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 转换调用 "implementation-defined or an implementation-defined signal is raised",这通常是预期的功能:urnt 中的值高于 INT_MAX "wrap around".

或者,迂腐的代码可以使用:

  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)时的问题。
参见