Skip to end of metadata
Go to start of metadata

Expressions that have an integral type can be added to or subtracted from a pointer, resulting in a value of the pointer type. If the resulting pointer is not a valid member of the container, or one past the last element of the container, the behavior of the additive operator is undefined. The C++ Standard, [expr.add], paragraph 5 [ISO/IEC 14882-2014], in part, states the following:

If both the pointer operand and the result point to elements of the same array object, or one past the last element of the array object, the evaluation shall not produce an overflow; otherwise, the behavior is undefined.

Because iterators are a generalization of pointers, the same constraints apply to additive operators with random access iterators. Specifically, the C++ Standard, [iterator.requirements.general], paragraph 5, states the following:

Just as a regular pointer to an array guarantees that there is a pointer value pointing past the last element of the array, so for any iterator type there is an iterator value that points past the last element of a corresponding sequence. These values are called past-the-end values. Values of an iterator i for which the expression *i is defined are called dereferenceable. The library never assumes that past-the-end values are dereferenceable.

Do not allow an expression of integral type to add to or subtract from a pointer or random access iterator when the resulting value would overflow the bounds of the container.

Noncompliant Code Example (std::vector)

In this noncompliant code example, a random access iterator from a std::vector is used in an additive expression, but the resulting value could be outside the bounds of the container rather than a past-the-end value.

#include <iostream>
#include <vector>
 
void f(const std::vector<int> &c) {
  for (auto i = c.begin(), e = i + 20; i != e; ++i) {
    std::cout << *i << std::endl;
  }
}

Compliant Solution (std::vector)

This compliant solution assumes that the programmer's intention was to process up to 20 items in the container. Instead of assuming all containers will have 20 or more elements, the size of the container is used to determine the upper bound on the addition.

#include <algorithm>
#include <vector>

void f(const std::vector<int> &c) {
  const std::vector<int>::size_type maxSize = 20;
  for (auto i = c.begin(), e = i + std::min(maxSize, c.size()); i != e; ++i) {
    // ...
  }
}

Risk Assessment

If adding or subtracting an integer to a pointer results in a reference to an element outside the array or one past the last element of the array object, the behavior is undefined but frequently leads to a buffer overflow or buffer underrun, which can often be exploited to run arbitrary code. Iterators and standard template library containers exhibit the same behavior and caveats as pointers and arrays.

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

CTR55-CPP

High

Likely

Medium

P18

L1

Automated Detection

Tool

Version

Checker

Description

LDRA tool suite
9.7.1

 

567 S

Enhanced Enforcement

Parasoft C/C++test

10.4.2

CERT_CPP-CTR55-a

Do not add or subtract a constant with a value greater than one from an iterator

Related Vulnerabilities

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

Related Guidelines

Bibliography

[Banahan 2003]Section 5.3, "Pointers"
Section 5.7, "Expressions Involving Pointers"
[ISO/IEC 14882-2014]

Subclause 5.7, "Additive Operators"
Subclause 24.2.1, "In General"

[VU#162289]



3 Comments

  1. About: Compliant Solution (Linear Address Space, std::uintptr_t).

    Problem 1:
    If len == 1 && (std::uintptr_t)(buf + 1) == 0, then len is incorrectly set to 0.

    Problem 2:
    bint + len < bint is not equivalent to (std::uintptr_t)(bint + len) < bint, because size_t may have greater a precision than uintptr_t.

    Problem 3:
    http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/stdint.h.html
    only guarantees lossless casts between uintptr_t and (void *).
    It says nothing about the relation between pointer arithmetic and uintptr_t arithmetic.  
    To me, it seems that uintptr_t has been defined for xor-linked-lists an nothing else.

    Didactic concern:
    The code snippet in question is a security problem in itself, not a 'solution' for a given security problem. Indeed, if the given length of a given array is wrong, no code can be correct/secure. But it is suggested that the correct length can be computed from wrap-around considerations.

    1. All three problems you state are actual issues with the compliant solution. Most especially, Problem 3; C only defines the modulo arithmetic for exact-width integers (uint32_t
      and friends), but not for uintptr_t.

      1. Some precisions for the interested reader.

        I believe that C defines modulo arithmetic for all unsigned integer types. From http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf

        6.2.5, 9: ... A computation involving unsigned operands can never overflow, because a result that cannot be represented by the resulting unsigned integer type is reduced modulo the number that is one greater than the largest value that can be represented by the resulting type.
        7.20.1.4, 1: The following type designates an unsigned integer type with the property that any valid pointer to void can be converted to this type, then converted back to pointer to void, and the result will compare equal to the original pointer: uintptr_t

        But even so, the relation between uintptr_t arithmetic and pointer arithmetic remains unspecified. From http://c-faq.com/null/machexamp.html
        Some 64-bit Cray machines represent int * in the lower 48 bits of a word; char * additionally uses some of the upper 16 bits to indicate a byte address within a word