Integer Overflow Vulnerability Pattern

From Guidance Share

Jump to: navigation, search

Contents

Context

The target application is written in a language that is not type safe.


Problem

Calculations that result in values larger than the datatype can represent.


Forces

  • Calculation stored in a primitive data type (such as short or integer).
  • Untrusted input can impact the calculation.
  • Absence of a sanity check on the result of the calculation.
  • Calculation result is used for memory allocation, buffer indexing or pointer arithmetic.


Solution

The most common forms are:

  • Failure to account for heterogeneous primitive data types
void RecordBytes(int maxGet)
{
  //this counter, as a short, does not have the same range as maxGet.
  short counter = 0;
  char buf[maxGet];
  while (counter < maxGet)
  {
    counter += getFromInput(buf+counter);
  }
 }
  • Mistaken operator precedence
void PartialRecordBytes(int maxGet)
{
  int counter = 0;
  //trying to allocate 3/4 of the size
  //but operator precedence makes an overflow possible
  int partialMaxGet = maxGet*3/4;
  char buf[partialMaxGet];
  while (counter < partialMaxGet)
  {
    counter += getFromInput(buf+counter);
  }
 }
  • Incrementing too far
int bytesRead = 0;
byte b;
do
{
  b = ReadByte();
  //since there may be more bytes to read than max_int
  //at which point bytesRead will overflow
  bytesRead++;
} while (b != NULL);
Personal tools