codeql icon indicating copy to clipboard operation
codeql copied to clipboard

C++: prototype for off-by-one in array-typed field

Open rdmarsh2 opened this issue 3 years ago • 1 comments
trafficstars

rdmarsh2 avatar Sep 23 '22 18:09 rdmarsh2

QHelp previews:

cpp/ql/src/experimental/Security/CWE/CWE-193/ConstantSizeArrayOffByOne.qhelp

Constant array overflow

The program performs an out-of-bounds read or write operation. In addition to causing program instability, techniques exist which may allow an attacker to use this vulnerability to execute arbitrary code.

Recommendation

Ensure that pointer dereferences are properly guarded to ensure that they cannot be used to read or write past the end of the allocation.

Example

The first example uses a for loop which is improperly bounded by a non-strict less-than operation and will write one position past the end of the array. The second example bounds the for loop properly with a strict less-than operation.

#define MAX_SIZE 1024

struct FixedArray {
  int buf[MAX_SIZE];
};

int main(){
  FixedArray arr;

  for(int i = 0; i <= MAX_SIZE; i++) {
    arr.buf[i] = 0; // BAD
  }

  for(int i = 0; i < MAX_SIZE; i++) {
    arr.buf[i] = 0; // GOOD
  }
}

References

github-actions[bot] avatar Sep 30 '22 19:09 github-actions[bot]

Also just a minor question about the title of the PR: There's nothing "prototypy" about this query anymore, right? That is, this is a fully-fledged query that we expect to promote to Code Scanning this coming quarter, correct?

MathiasVP avatar Oct 03 '22 08:10 MathiasVP