ABV.ITERATOR
Buffer overflow-array index out of bounds in an iteration
ABV.ITERATOR checks for out-of-bounds access to an array element using a pointer in an iteration through the array. The checker flags any code in which a buffer overflow could occur as a result of this situation.
Vulnerability and risk
Consequences of buffer overflow include valid data being overwritten and execution of arbitrary and potentially malicious code.
Vulnerable code example 1
int example1()
{
int a[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
int *p;
for (p = a ; p < a + 10; p++)
{
if (bar(*p) < 5)
break;
}
return *p; // ABV.ITERATOR
}
Klocwork produces a buffer overflow report for line 10 indicating that pointer 'p' is used when its value may exceed the bounds of array 'a'. Pointer 'p' is assigned to 'a' and iterated at line 5. In this case, the iteration may cause array 'a' to overrun its limit of 10.
Fixed code example 1
int example1()
{
int a[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
int *p;
for (p = a ; p < a + 10; p++)
{
if (bar(*p) < 5)
break;
}
if (p < a + 10)
return *p;
return 0;
}
In the fixed code example, a check is made at line 10 to ensure that array 'a' can't overflow.
Vulnerable code example 2
int example2(int x)
{
int a[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
int *p = bar (a, x); //function returns a pointer to some element in "a"
if (p < a + 5)
return *p;
return p[5]; // DEFECT: p[5] points to a[11] or beyond
}
Klocwork produces an ABV.ITERATOR report at line 8, indicating that array 'a' will overflow after the iteration.
Fixed code example 2
int example2(int x)
{
int a[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
int *p = bar (a, x); //function returns a pointer to some element in "a"
if (p >= a + 5)
return *p;
return p[5];
}
In the fixed code example, the syntax is corrected in line 5, and the buffer overflow is avoided.
Related checkers
External guidance
- CERT ARR00-C: Understand how arrays work
- CERT ENV01-C: Do not make assumptions about the size of an environment variable
- CERT EXP08-C: Ensure pointer arithmetic is used correctly
- CWE-119: Improper Restriction of Operations within the Bounds of a Memory Buffer
- CWE-120: Buffer Copy without Checking Size of Input ('Classic Buffer Overflow')
- CWE-124: Buffer Underwrite ('Buffer Underflow')
- CWE-125: Out-of-bounds Read
- CWE-787: Out-of-bounds Write
- CWE-805: Buffer Access with Incorrect Length Value
- CWE-806: Buffer Access Using Size of Source Buffer
- STIG-ID:APP3590.1 Application is vulnerable to buffer overflows
Security training
Application security training materials provided by Secure Code Warrior.
Extension
This checker can be extended through the Klocwork knowledge base. See Tuning C/C++ analysis for more information.