Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Since the input is unbounded, the following code could lead to a buffer overflow

Code Block
bgColor#FFcccc

char buf[12];
cin >> buf;

Non-compliant solution 1 (operator<<())

To solve this problem, one can be tempted to use the width method of the ios_base class, but there still is a trap.

Code Block
bgColor#ffcccc

char buf_one[12];
char buf_two[12];
cin.width(12);
cin >> buf_one;
cin >> buf_two;

Wiki Markup
In this example, the first read won't overflow, but the second still could, because as the C+\+ standard states : "operator>> extracts characters and stores them into successive locations of an array \[...\] operator>> then calls width(0)." Which means that width should be called every time you use the >> operator with a bounded array.

...

Non-compliant solution 2 (operator<<())

While the following doesn't suffer of the same problem as the previous, it still has some :

Code Block
bgColor#ccccff#ffcccc

char buf_one[12];
char buf_two[12];
cin.width(12);
cin >> buf_one;
cin.width(12);
cin >> buf_two;

Wiki Markup
because, as the C+\+ standard states, "If width() is greater than zero, n is width() \[...\] n-1 characters are stored \[...\] Operator>> then stores a null byte (charT()) in the next position, which may be the first position if no characters were extracted." The input could therefore be truncated, leading to information lost, and to a possible vulnerability. 
In this particular example, if the user enters a string longer than 11 (11 characters + the NULL terminating character automatically appended by the >> operator equals 12 characters), the 12th and all subsequent characters will be lost.

Compliant solution (operator<<())

To avoid this truncation problem, it would be better to use an instance of the string class to store the input, as it is dynamically resized to fit the input.

Code Block
bgColor#ccccff

string input;
cinconst >> inputchar *buf_one;
const char *array = inputbuf_two;
string string_one;
string string_two;
cin >> string_one;
cin >> string_two;
buf_one = string_one.c_str();
buf_two = string_two.c_str();

The only problem with this code is that it will be necessary to copy the characters in another array if they are to be modifiedBy special attention to the const, and you may want to read STR45-CPP for details on how to handle the output of c_str().

Risk Assessment

Copying data from an unbounded source to a buffer of fixed size may result in a buffer overflow.

...