When performing pointer arithmetic, the size of the value to add to a pointer is automatically scaled to the size of the pointer's type. For instance, when adding a value to a pointer to a four-byte integer, the value is scaled by a factor of four and then added to the pointer. Failing to understand how pointer arithmetic works can lead to miscalculations that result in serious errors, such as buffer overflows.
In this non-compliant code example derived from \[[Dowd|AA. C References#Dowd 06]], integer values returned by {{parseint(getdata())}} are stored into an array of {{INTBUFSIZE}} elements of type {{int}} called {{buf}}. If data is available for insertion into {{buf}} (which is indicated by {{havedata()}}) and {{buf_ptr}} has not been incremented past {{buf + sizeof(buf)}}, an integer value is stored at the address referenced by {{buf_ptr}}. However, the {{sizeof}} operator returns the total number of bytes in {{buf}} which is typically a multiple of the number of elements in {{buf}}. This value is scaled to the size of an integer and added to {{buf}}. As a result, the check to make sure integers are not written past the end of {{buf}} is incorrect and a buffer overflow is possible. |
int buf[INTBUFSIZE]; int *buf_ptr = buf; while (havedata() && buf_ptr < buf + sizeof(buf)) { *buf_ptr++ = parseint(getdata()); } |
In this compliant solution, the size of buf
is added directly to buf
and used as an upper bound. The integer literal is scaled to the size of an integer and the upper bound of buf
is checked correctly.
int buf[INTBUFSIZE]; int *buf_ptr = buf; while (havedata() && buf_ptr < (buf + INTBUFSIZE)) { *buf_ptr++ = parseint(getdata()); } |
Failure to understand and properly use pointer arithmetic can allow an attacker to execute arbitrary code.
Rule |
Severity |
Likelihood |
Remediation Cost |
Priority |
Level |
---|---|---|---|---|---|
EXP08-A |
3 (high) |
2 (probable) |
1 (high) |
P6 |
L2 |
Examples of vulnerabilities resulting from the violation of this rule can be found on the CERT website.
\[[Dowd|AA. C References#Dowd 06]\] Chapter 6, "C Language Issues" (Vulnerabilities) |