CESA-2007-003 - rev 1


[See all my vulnerabilities at http://scary.beasts.org/security]

C++ language new[] operator integer overflow



Programs affected: unknown
Advisory release date: Sep 6th 2007.
Severity: only broken programs affected

This isn't so much a vulnerability as an interesting hardening recommendation. I noticed this a while back but didn't get any traction on changing this (probably because I was too busy to push too hard or make a patch). Maybe this note will inspire debate and patches.

Take the following C++ program:

#include <stdio.h>

int main(int argc, const char* argv[]) {
  unsigned int num = 1 << 30;
  int* p = new int[num];
  printf("%p\n", p);
  for (int i = 0; i < num; ++i) {
    p[i] = 0;
  }
}
Assuming you have a 32-bit platform, this program will crash. (64-bit untested). Of course, the program is buggy - it allows a huge value to get passed to operator new. Generally, untrusted values shouldn't be used as the parameter to operator new. A vulnerable program might pull a 32-bit integer out of a protocol or a binary file format and use that as the parameter to operator new.

What is interesting is that on my platform (Linux, gcc toolchain, modern install), the crash is an out of bound write. Presumably, the space allocation went something like:

num * sizeof(int)
Which happens to equal 0 in this case, using 32-bit width for allocation size. On modern glibc, a zero sized allocation returns a valid pointer (if it didn't, we could arrange for the integer overflow to lead to a small value instead of a zero one).

It would be nice if this integer overflow in operator new were removed so that buggy programs just crash with a bad_alloc rather than having an exploitable heap overflow condition. Note that this integer overflow is very similar to one in calloc(), which was fixed.

As a reader exercise, why not play with searching Google Code Search for things like:

lang:c++ "new int["
Do let me know if you find anything interesting :)


CESA-2007-003 - rev 1
Chris Evans
scarybeasts@gmail.com