All of the interesting technological, artistic or just plain fun subjects I'd investigate if I had an infinite number of lifetimes. In other words, a dumping ground...

Thursday 15 May 2008

GCC FORTIFY_SOURCE



GCC compile time buffer checks (FORTIFY SOURCE)

In Fedora Core 3 and Red Hat Enterprise Linux 4, gcc and glibc gained a feature called "FORTIFY_SOURCE" that will detect and prevent a subset of the buffer overflows before they can do damage. While this feature is present in these two releases, it's not used for significant portions of the Fedora Core 3 and Red Hat Enterprise Linux 4 distributions itself. This is different for Fedora Core 4; here almost the entire distribution is compiled with this feature enabled.

The idea behind FORTIFY_SOURCE is relatively simple: there are cases where the compiler can know the size of a buffer (if it's a fixed sized buffer on the stack, as in the example, or if the buffer just came from a malloc() function call). With a known buffer size, functions that operate on the buffer can make sure the buffer will not overflow.

Example:

void foo(char *string)
{
char buf[20];
strcpy(buf, string);
}

In the example, gcc knows that the buf variable is 20 bytes in size. When this code is compiled with FORTIFY_SOURCE enabled, gcc uses a special version of strcpy() which asks gcc for the the size of the destination buffer. Since the size is known (here, 20 bytes), the strcpy() code will not copy after 20 bytes. If there is more than 20 bytes to copy, the program is aborted. If gcc proves at compile time that this buffer will overflow, it also issues a warning.

There are many functions in the standard glibc library that operate on buffers. In Fedora Core 4, the majority of these functions use this extra information from gcc to do the sanity checks.

The FORTIFY_SOURCE feature can be enabled for your own application in Fedora Core 3 and 4 and Red Hat Enterprise Linux 4 by passing the following argument to gcc:

-D_FORTIFY_SOURCE=2

You can see how often a checking function is used in an application via the following command:

objdump -d <program or library> | grep call | grep _chk | wc -l

If this is non-zero, FORTIFY_SOURCE is active. However if the value returned is zero, FORTIFY_SOURCE either might not be enabled, or the program code is such that FORTIFY_SOURCE is not applicable (for example: secure code that has no static buffers and always checks buffer sizes, and thus FORTIFY_SOURCE cannot identify any potentially dangerous operations in the program).


No comments:

tim's shared items

Add to Google Reader or Homepage