簡體   English   中英

如何解決強化報告中的整數溢出? (C代碼)

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

當我分配一個緩沖區(通過讀取頭的緩沖區大小)時,我有一個關於圖像功能的函數。 強化報告在這里告訴我“整數溢出”。 但是,無論我修復代碼還是檢查顏色值,強化報告仍然告訴我“整數溢出”

有人有什么建議嗎?

碼:

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”位移入符號位時,將int左移就有可能發生不確定的行為 (UB)。

這可以通過some_int << 8任意int值發生。

getc()返回一個unsigned char范圍或負EOF 左移EOF是UB。 向左移128和128 << 24這樣的值是UB。

而是使用無符號數學從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轉換調用“實現定義的信號或實現定義的信號被發出”,這通常是預期的功能: urnturnt以上的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);

INT_MAX < 134217728 (28位int )時, 1024 * 1024 * 128是一個問題。
請參閱有不使用1000 * 1000 * 1000的原因

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM