CERT
Skip to end of metadata
Go to start of metadata

When performing pointer arithmetic, the size of the value to add to a pointer is automatically scaled to the size of the type of the pointed-to object. For instance, when adding a value to the byte address of a 4-byte integer, the value is scaled by a factor of 4 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.

Noncompliant Code Example

In this noncompliant code example, integer values returned by parseint(getdata()) are stored into an array of INTBUFSIZE elements of type int called buf [Dowd 2006]. 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.

Compliant Solution

In this compliant solution, the size of buf, INTBUFSIZE, is added directly to buf and used as an upper bound. The integer literal INTBUFSIZE is scaled to the size of an integer, and the upper bound of buf is checked correctly.

An arguably better solution is to use the address of the nonexistent element following the end of the array, as follows:

This solution works because the C Standard guarantees the address of buf[INTBUFSIZE] even though no such element exists.

Noncompliant Code Example

This noncompliant code example is based on a flaw in the OpenBSD operating system. An integer, skip, is added as an offset to a pointer of type struct big. The adjusted pointer is then used as a destination address in a call to memset(). However, when skip is added to the struct big 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 scaling results in the call to memset() writing to unintended memory.

A similar situation occurred in OpenBSD's make command [Murenin 2007].

Compliant Solution

To correct this example, the struct big pointer is cast as a char *, which causes skip to be scaled by a factor of 1:

Risk Assessment

Failure to understand and properly use pointer arithmetic can allow an attacker to execute arbitrary code.

Recommendation

Severity

Likelihood

Remediation Cost

Priority

Level

EXP08-C

High

Probable

High

P6

L2

Automated Detection

Tool

Version

Checker

Description

Astrée17.04i Supported, but no explicit checker
CodeSonar4.4

LANG.STRUCT.PARITH

LANG.MEM.BO
LANG.MEM.BU
LANG.STRUCT.PBB
LANG.STRUCT.PPE
LANG.MEM.TBA
LANG.MEM.TO
LANG.MEM.TU

Pointer arithmetic

Buffer overrun
Buffer underrun
Pointer before beginning of object
Pointer past end of object
Tainted buffer access
Type overrun
Type underrun

Klocwork2017ABV.ITERATOR
ABV.GENERAL
 
LDRA tool suite9.5.6

45 D
53 D
54 D
438 S
576 S

Partially implemented

Parasoft C/C++test9.5

MISRA-101

BD-PB-ARRAY

Checks all array access, not just pointer arithmetic
Parasoft Insure++  Runtime analysis for over- or under- read or write
Polyspace Bug FinderR2016a

Incorrect pointer scaling

Pointer access out of bounds

Implicit scaling in pointer arithmetic might be ignored

Pointer dereferenced outside its bounds

PRQA QA-C9.3

0488, 2930, 2931, 2932, 2933, 2934

Partially implemented

 

How long is 4 yards plus 3 feet? It is obvious from elementary arithmetic that any answer involving 7 is wrong, as the student did not take the units into account. The right method is to convert both numbers to reflect the same units.

The examples in this rule reflect both a correct and an incorrect way to handle comparisons of numbers representing different things (either single bytes or multibyte data structures). The noncompliant examples just add the numbers without regard to units, whereas the compliant solutions use type casts to convert one number to the appropriate unit of the other number.

ROSE can catch both noncompliant examples by searching for pointer arithmetic expressions involving different units. The "different units" is the tricky part, but you can try to identify an expression's units using some simple heuristics:

  • A pointer to a foo object has foo as the unit.
  • A pointer to char * has byte as the unit.
  • Any sizeof or offsetof expression also has unit byte as the unit.
  • Any variable used in an index to an array of foo objects (e.g., foo[variable]) has foo as the unit.

In addition to pointer arithmetic expressions, you can also hunt for array index expressions, as array[index] is merely shorthand for "array + index."

Related Vulnerabilities

Search for vulnerabilities resulting from the violation of this rule on the CERT website.

Related Guidelines

SEI CERT C++ Coding StandardEXP08-CPP. Ensure pointer arithmetic is used correctly
ISO/IEC TR 24772:2013Pointer Casting and Pointer Type Changes [HFC]
Pointer Arithmetic [RVG]
ISO/IEC TS 17961Forming or using out-of-bounds pointers or array subscripts [invptr]
MISRA C:2012Rule 18.1 (required)
Rule 18.2 (required)
Rule 18.3 (required)
Rule 18.4 (advisory)
MITRE CWECWE-468, Incorrect pointer scaling

Bibliography

[Dowd 2006]Chapter 6, "C Language Issues"
[Murenin 2007] 

 


7 Comments

  1. Shouldn't the second example be using offsetof() instead of trying to count offsets directly?

    Or wouldn't the code be a lot easier to understand if it had been rewritten as:

    *Poof* - no funky pointer stuff.

    1. I implemented the offsetof() solution because it looks cleaner to me and does not add run-time overhead.

      1. The offsetof() solution is the right one, though at times I do make minor concessions to runtime performance if I think it will make the code easier to understand by the next guy who has to work on my code. Clarity breeds maintainability.

  2. The first compliant example could alternatively use sizeof(buf)/sizeof(buf[0]), which represents the standard idiom for checking the size of an array.

  3. The first example is better coded:

    since "the Standard endorses existing practice by guaranteeing that it's permissible to use the address of
    buf[INTBUFSIZE] even though no such element exists." (from The C Book, by Mike Banahan). This is clearer and less
    error-prone than the alternatives

    1. OK, it took me a while, but I'll buy this. Added as a "arguably better" compliant solution.

  4. As i just commented elsewhere, this problem this practice attempts to prevent is the subject of ARR30-C. Do not form or use out of bounds pointers or array subscripts. I suggest this recommendation be moved into 99. The Void (perhaps after copying the first NCCE into ARR30-C, if we'd like to preserve it).