January 9, 2014

Using Pintools to Detect Bugs II: Overlap of Regions

There are functions that can take source and destination parameters to copy data. That functions include the followings: strncpy(), strncat(), memcpy(), wcsncpy(), wcsncat(), strcat(), strcpy(), wcscat(), wcscpy(), CopyMemory(), sscanf(), printf(), swscanf(), swprintf(). If the destination and source regions overlap the behavior is undefined. This really means one of the regions can get partly overwritten when copying. I wrote about this earlier.

Some time ago I wrote a tool to detect such errors runtime and I used Pin framework. Though I've never seen an exploitable bug regarding this classification it's still valuable to detect these issues as the attacker could write memory that he's not supposed to. This could lead to enter the program in an inconsistent state.

The tool I wrote produces the following straightforward output on the test sample.
Overlap of source and destination regions at 6c79396f in wcsncat(021b1ee8,021b1eec,8)
  Stack
    001efd90 7c 10 eb 00 e8 1e 1b 02 ec 1e 1b 02 08 00 00 00
    001efda0 74 33 eb 00 01 00 00 00 07 12 eb 00 01 00 00 00
    001efdb0 58 3e 1b 02 40 5c 1b 02 10 5a cc 31 00 00 00 00
    001efdc0 00 00 00 00 00 e0 fd 7e 00 00 00 00 00 00 00 00
  Source
    021b1eec 75 00 72 00 63 00 65 00 20 00 73 00 74 00 72 00
    021b1efc 69 00 6e 00 67 00 00 00 00 00 00 00 00 00 00 00
    021b1f0c 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
    021b1f1c 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  Destination
    021b1ee8 73 00 6f 00 75 00 72 00 63 00 65 00 20 00 73 00
    021b1ef8 74 00 72 00 69 00 6e 00 67 00 00 00 00 00 00 00
    021b1f08 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
    021b1f18 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 
You may ask what's the news to detect this bug as Valgrind can do for ages. Well, my approach is not to use symbols, source code, or any debug information so I can apply my tests against arbitrary binaries.

Even just few string copy functions were added to the tool I had found plenty low-severity bugs in high-profile applications by this approach.

Here is the tool. Feel free to improve it according to your needs.

UPDATE 15/January/2014 Added CopyMemory() to the list.
UPDATE 2/February/2014 Added sscanf(), printf(), swscanf(), swprintf() to the list. Reference.
  This blog is written and maintained by Attila Suszter. Read in Feed Reader.