Versions Compared

Key

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

...

In this non-compliant code example, an integer overflow is specifically looked for by checking whether length + 1 == 0 (that is, integer wrap around has occurred). If the test passes, a wrapper to malloc() is called to allocate the appropriate data block. In a program compiled using an ILP32 compilerWhen sizeof(int) == sizeof(long), this code runs as expected, but in an LP64 environmentif sizeof(long) > sizeof(int), an integer overflow can occur because when length is now a 64-bit value. The result of the expression, however, is truncated to 32 bits when passed as an argument passed in to alloc() because it takes the result is truncated down to an unsigned int argument.

Code Block
bgColor#FFcccc
void *alloc(unsigned int blocksize) {
  return malloc(blocksize);
}

int read_counted_string(int fd) {
  unsigned long length;
  unsigned char *data;

  if (read_integer_from_network(fd, &length) < 0) {
    return -1;
  }

  if (length + 1 == 0) {
    /* handle integer overflow */
  }

  data = (unsigned char*)alloc(length + 1);

  if (read_network_data(fd, data, length) < 0) {
    free(data);
    return -1;
  }
  data[length] = '\0';

  /* ... */
  free( data);
  return 0;
}

...