Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Migrated to Confluence 5.3

The index operators

Code Block
const_reference operator[](size_type pos) const;
reference operator[](size_type pos);

return the character stored at the specified position if pos < size(). If pos == size(), the const
version returns the terminating null character type value. Otherwise, the behavior is undefined.

In any case, the behavior of the index operators is unchecked (no exceptions are thrown).

Non-Compliant Code Example

The behavior of this non-compliant example is undefined because the index i used to reference bs may be outside the range of bs, causing a write-out-of-bounds error.

Code Block
bgColor#FFcccc
langcpp
string bs("01234567");
size_t i = f();

bs[i] = '\0';

This program does not typically raise an exception and may be exploited to overwrite memory at a specified location.

Compliant Solution

This compliant solution uses the basic_string at() method, which behaves in a similar fashion to the index operator[] but throws an out_of_range exception if pos >= size().

Code Block
bgColor#ccccff
langcpp
string bs("01234567");
try {
  size_t i = f();
  bs.at(i) = '\0';
}
catch (...) {
  cerr << "Index out of range" << endl;
}

In any case, the behavior of the index operators is unchecked (no exceptions are thrown).

Non-Compliant Code Example

The behavior of this non-compliant example is undefined because the size() of bs is 8 but the index used to reference bs ranges from 0 through 99.

Code Block
bgColor#FFcccc
langcpp
string bs("01234567");
for (int i=0; i < 100; i++) {
  bs[i] = '\0';
}

This program does not typically raise an exception and is likely to crash.

Compliant Solution

Use the fill algorithm to assign the value '\0' to evey element in the specified range:

Code Block
bgColor#ccccff
langcpp
size_t const max_fill = 100;
std::string bs("01234567");

fill(bs.begin(), bs.begin()+std::min(max_fill, bs.length()), '\0' );

The range is specified as starting from the beginning of the string and ending at the minimum of the string length or the max_fill constant value of 100.

Risk Assessment

Unchecked element access can lead to out-of-bounds reads and writes and write-anywhere exploits. These exploits can in turn lead to the execution of arbitrary code with the permissions of the vulnerable process.

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

STR39-CPP

high

likely

high

P9

L2

Bibliography

[Seacord 05] Chapter 2 Strings
[ISO/IEC 14882-2003] Section 21.3.4 basic_string element access


STR38-CPP. Use valid references, pointers, and iterators to reference string objects      07. Characters and Strings (STR)      08. Memory Management (MEM)