CodeQL documentation

Invalid pointer dereference

ID: cpp/invalid-pointer-deref
Kind: path-problem
Security severity: 9.3
Severity: error
Precision: medium
Tags:
   - reliability
   - security
   - external/cwe/cwe-119
   - external/cwe/cwe-125
   - external/cwe/cwe-193
   - external/cwe/cwe-787
Query suites:
   - cpp-security-extended.qls
   - cpp-security-and-quality.qls

Click to see the query in the CodeQL repository

The program performs an out-of-bounds read or write operation, which can cause program instability. In addition, attackers may take advantage of the situation, and implement techniques 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 allocates a buffer of size size and creates a local variable that stores the location that is one byte past the end of the allocation. This local variable is then dereferenced, which results in an out-of-bounds write. The second example subtracts one from the end variable before dereferencing it. This subtraction ensures that the write correctly updates the final byte of the allocation.

void *malloc(unsigned);
unsigned get_size();
void write_data(const unsigned char*, const unsigned char*);

int main(int argc, char* argv[]) {
  unsigned size = get_size();
  
  {
    unsigned char *begin = (unsigned char*)malloc(size);
    if(!begin) return -1;

    unsigned char* end = begin + size;
    write_data(begin, end);
    *end = '\0'; // BAD: Out-of-bounds write
  }

  {
    unsigned char *begin = (unsigned char*)malloc(size);
    if(!begin) return -1;

    unsigned char* end = begin + size;
    write_data(begin, end);
    *(end - 1) = '\0'; // GOOD: writing to the last byte
  }

}

References

  • © GitHub, Inc.
  • Terms
  • Privacy