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);unsignedget_size();voidwrite_data(constunsignedchar*,constunsignedchar*);intmain(intargc,char*argv[]){unsignedsize=get_size();{unsignedchar*begin=(unsignedchar*)malloc(size);if(!begin)return-1;unsignedchar*end=begin+size;write_data(begin,end);*end='\0';// BAD: Out-of-bounds write}{unsignedchar*begin=(unsignedchar*)malloc(size);if(!begin)return-1;unsignedchar*end=begin+size;write_data(begin,end);*(end-1)='\0';// GOOD: writing to the last byte}}
References¶
CERT C Coding Standard: ARR30-C. Do not form or use out-of-bounds pointers or array subscripts.
OWASP: Buffer Overflow.
Common Weakness Enumeration: CWE-119.
Common Weakness Enumeration: CWE-125.
Common Weakness Enumeration: CWE-193.
Common Weakness Enumeration: CWE-787.