Test case 5

Read overflow, on compile-time allocated memory. We attempt a read on a compile-time allocated memory buffer, after its last legally accessible location:

/* test case 5 : out-of-bounds : read overflow [on compile-time memory] */
static void read_overflow_compilemem(void)
{
char arr[5], tmp[8];

memset(arr, 'a', 5);
memset(tmp, 't', 8);
tmp[7] = '';

printf("arr = %s ", arr); /* Bug: read buffer overflow */
}

The way this test case is designed, we have two buffers arranged sequentially in memory. The bug: we deliberately do not null-terminate the first buffer (but do so on the second one), so, the printf(3) that will emit on arr continues reading into the second buffer, tmp. What if the tmp buffer contains secrets? 

The point, of course is that the compiler cannot catch this seemingly obvious bug. Also, do realize that here we're writing small, simple, easy-to-read test cases; on a real project with a few million lines of code, defects such as this are easy to miss.

Here is the sample output:

$ ./membugs 2>&1 | grep -w 5
option = 5 : out-of-bounds : read overflow [on compile-time memory]
$ ./membugs 5
arr = aaaaattttttt
$

Hey, we got to read the secret memory of tmp.

In fact, tools such as ASan (Address Sanitizer, seen in the next chapter), classify this bug as a stack buffer overflow.

As an aside, on our Fedora 28 workstation, we just get junk from the second buffer in this test case:

$ ./membugs 5
arr = aaaaa0<5=�
$ ./membugs 5
arr = aaaaa�:��
$

This shows us that these bugs can reveal themselves differently, depending on the compiler version, the glibc version, and the machine hardware. 

An always useful testing technique is to try to run your test cases on as many hardware/software variants as possible. Hidden bugs may be exposed! Think of instances such as endianness issues, compiler optimization (padding, packing), and platform-specific alignments.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.142.123.87