...
Wiki Markup |
---|
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. |
...
Code Block |
---|
|
int buf[INTBUFSIZE];
int *buf_ptr = buf;
while (havedata() && buf_ptr < (buf + INTBUFSIZE)) {
*buf_ptr++ = parseint(getdata());
}
|
Non-Compliant Code Example
Wiki Markup |
---|
The following example is based on a flaw discovered in the OpenBsd operating system \[[ref]\]. An integer, {{offset}}, is added as an offset to a pointer of type {{struct big}} the sum of which is used as a destination address in a call to {{memset}}. However, when {{offset}} is added to the {{struct bug}} pointer it is automatically scaled by the size of {{struct big}}, which is 32 bytes (assuming 4 byte integers, 8 byte long long integers, and no structure padding). This results in the call to {{memset}} writing to unintended memory. |
Code Block |
---|
|
struct big {
unsigned long long member_1; /* typically 8 bytes */
unsigned long long member_2; /* typically 8 bytes */
unsigned long long member_3; /* typically 8 bytes */
int member_4; /* typically 4 bytes */
int member_5; /* typically 4 bytes */
};
/* ... */
size_t offset = sizeof(unsigned long long);
struct big *s = malloc(sizeof(struct big));
if (!s) {
/* Handle malloc() error */
}
memset(s + offset, 0, sizeof (struct big) - offset);
/* ... */
free(s);
|
Risk Assessment
Failure to understand and properly use pointer arithmetic can allow an attacker to execute arbitrary code.
...