...
Noncompliant Code Example
Since Because the input is unbounded, the following code could lead to a buffer overflow:
...
To solve this problem, it may be tempting to use the std::ios_base::width()
method, but there still is a trap, as shown in this noncompliant code example. In this example, the first read won't will not overflow, but the second read still could. The C++ Standard, [istream.extractors], paragraphs 7-9 describe 7–9, describes the behavior of operator>>(basic_istream &, charT *)
, and states in part [ISO/IEC 14882-2014]:
operator>>
then stores a null byte (charT()
) in the next position, which may be the first position if no characters were extracted.operator>>
then callswidth(0)
.
ThusConsequently, it is necessary to call width()
prior to each operator>>
call passing a bounded array.
...
The best solution for ensuring that data is not truncated , and for guarding against buffer overflows are guarded against, is to use std::string
instead of a bounded array, as in this compliant solution:
...
In this noncompliant example, the unformatted input function std::basic_istream<T>::read()
is used to read an unformatted character array of 32 characters from the given file. However, the read()
function does not guarantee that the string will be null terminated, so the subsequent of of the std::string
constructor results in undefined behavior if the character array does not contain a null terminator.
...
This compliant solution continues to assume that the input from the file is exactly 32 characters, and instead of inserting a null terminator, it constructs the std::string
object based on the size. If the size of the input is uncertain, it is better to use std::basic_istream<T>::readsome()
or a formatted input function, depending on need.
...
Copying string data to a buffer that is too small to hold that data results in a buffer overflow. Attackers can exploit this condition to execute arbitrary code with the permissions of the vulnerable process.
...
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
...